Foros del Web » Programando para Internet » Javascript »

Ordenar articulos por fecha

Estas en el tema de Ordenar articulos por fecha en el foro de Javascript en Foros del Web. Hola chicos, espero puedan ayudarme. Necesito ordenar los artículos por fecha, pero la fecha debe ser ingresada a mano. Es decir, no puedo utilizar la ...
  #1 (permalink)  
Antiguo 07/10/2008, 14:16
 
Fecha de Ingreso: septiembre-2008
Mensajes: 12
Antigüedad: 15 años, 7 meses
Puntos: 0
Ordenar articulos por fecha

Hola chicos, espero puedan ayudarme. Necesito ordenar los artículos por fecha, pero la fecha debe ser ingresada a mano. Es decir, no puedo utilizar la fecha ni del sistema ni del servidor. En este caso, el usuario es quien pone la fecha del artículo. Por ejemplo:

El usuario ingresa: 12 de Abril de 2008. Luego ingresa 11 de Abril de 2006. Y el sistema debe mostrar:

11 de Abril de 2006
12 de Abril de 2008

Esto debe de ser así porque el usuario no quiere atarse a ningún formato de fechas.

Además puede ser el caso que desee ingresar: Lunes 6 y martes 7 de Octubre. Luego ingresa jUEVES 8 de Ocubre. Entonces el sistema debe mostrar:

Lunes 6 y martes 7 de Octubre
jUEVES 8 de Octubre

Por eso el campo fecha no tendría que ser del tipo date, sino del timpo longtext o varchar.

Ejemplo de los datos que tiene cada artículo:

Título: Vendo mi auto
Fecha: Martes 11 y Miércoles 12 de Noviembre.

Otro ejemplo:


Título: Vendo mi auto
Fecha: Lunes 10 de Noviembre.

Está claro que cuando el usuario ingrese una fecha, el resto de los ingresos de fecha, deberán tener el mismo formato.

Por ejemplo: Supongamos que la BD de articulos esta vacia y el usuario va a ingresar el primer articulo y al hacerlo elige este formato de fecha: Martes 11 y Miércoles 12 de Noviembre; en este caso, todos los artículos que sean publicados de aquí en más deberán tener ese formato para poder ser ordenados correctamente. De igual manera, si el usuario opta por ingresar como fecha: 10 de Mayo de 2008 el resto de los artículos deberán tener el mismo formato.

Espero haberme explicado !

MUCHAS GRACIAS POR SU AYUDA !
  #2 (permalink)  
Antiguo 07/10/2008, 16:45
Avatar de Genetix  
Fecha de Ingreso: febrero-2002
Ubicación: Lima - Perú
Mensajes: 1.600
Antigüedad: 22 años, 2 meses
Puntos: 45
Respuesta: Ordenar articulos por fecha

Hola
Pues no me parece correcto lo que deseas hacer, vas a tener muchos problemas
Si usas un campo que no es tipo date tus fechas jamas se van ordenar correctamente y vas ser imposible hacer consultas como por ejemplo buscar un rango

Lo que puedes hacer es formatear la salida de la fecha y darle la forma que desees , de esa manera no vas a tener problemas.


Saludos!
__________________
"El conocimiento nos hace responsables."
twitter: @benjamingb
blog personal: http://codigolinea.com
ZF Manual en español http://manual.zfdes.com
  #3 (permalink)  
Antiguo 07/10/2008, 16:51
 
Fecha de Ingreso: mayo-2006
Ubicación: Bogotá
Mensajes: 2.061
Antigüedad: 18 años
Puntos: 50
Respuesta: Ordenar articulos por fecha

yo de usted colocaria un ode esos scripts javascript que caergan un mini calendario para seleccionar la fecha. Son faciles de usar e implementar y asi usted puede determinar el formato con el que recibe la fecha


para lo de que puede tener varias fechas al tiempo lo que se me ocurre es que se cree una tabla de fechas x registro con el id del registro al que pertenece la fecha
y la fecha asignada por el usuario y asi el registro podra tener miles de fechas y como hay si puede poner el campo datetime pues puede ordenar por fecha


edspero le sirva mi ayuda cualquier cosa no dude en preguntar
  #4 (permalink)  
Antiguo 08/10/2008, 06:38
 
Fecha de Ingreso: septiembre-2008
Mensajes: 12
Antigüedad: 15 años, 7 meses
Puntos: 0
Respuesta: Ordenar articulos por fecha

Muchas gracias por contestar tan pronto ! La verdad es que necesito terminar esto ! Voy a intentar implementar uno de esos calendarios con javascript !

Una vez más, muchas gracias por su ayuda ! Cualquier cosa los vuelvo a molestar :)

Saludos !
  #5 (permalink)  
Antiguo 08/10/2008, 10:09
 
Fecha de Ingreso: septiembre-2008
Mensajes: 12
Antigüedad: 15 años, 7 meses
Puntos: 0
Respuesta: Ordenar articulos por fecha

Chicos ! de nuevo yo ! Estoy intentando implementar el calendario de javascript pero no me funciona. El tema es que la pagina que envía el formulario para luego procesarlo y hacer los correspondientes inserts en la BD lo estoy generando con php. Es decir, estoy escribiendo toda la pagina con echo "...";.

Buscando en google encontré un script para calendarios en javascript. A continuación les muestro el código.

El Paso uno sería escribir esto entre el <head></head>

<script language="javascript">
// Flooble Dynamic Calendar.
// Copyright (c) 2004 by Animus Pactum Consulting Inc.
//---------------------------------------------------------------------
// You may use this code freely on your site as long as you do not make
// modifications to it other than editing the stylesheet settings to
// make it fit your design. You may not remove this notice or any links
// to flooble.com.
// More information about this script is available at
// http://www.flooble.com/scripts/calendar.php
//--Global Stuff-------------------------------------------------------
var fc_ie = false;
if (document.all) { fc_ie = true; }

var calendars = Array();
var fc_months = Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var fc_openCal;

var fc_calCount = 0;

function getCalendar(fieldId) {
return calendars[fieldId];
}

function displayCalendarFor(fieldId) {
var formElement = fc_getObj(fieldId);
displayCalendar(formElement);
}

function displayCalendar(formElement) {
if (!formElement.id) {
formElement.id = fc_calCount++;
}
var cal = calendars[formElement.id];
if (typeof(cal) == 'undefined') {
cal = new floobleCalendar();
cal.setElement(formElement);
calendars[formElement.id] = cal;
}
if (cal.shown) {
cal.hide();
} else {
cal.show();
}
}

function display3FieldCalendar(me, de, ye) {
if (!me.id) { me.id = fc_calCount++; }
if (!de.id) { de.id = fc_calCount++; }
if (!ye.id) { ye.id = fc_calCount++; }
var id = me.id + '-' + de.id + '-' + ye.id;
var cal = calendars[id];
if (typeof(cal) == 'undefined') {
cal = new floobleCalendar();
cal.setElements(me, de, ye);
calendars[id] = cal;
}
if (cal.shown) {
cal.hide();
} else {
cal.show();
}
}

//--Class Stuff--------------------------------------------------
  #6 (permalink)  
Antiguo 08/10/2008, 10:12
 
Fecha de Ingreso: septiembre-2008
Mensajes: 12
Antigüedad: 15 años, 7 meses
Puntos: 0
Respuesta: Ordenar articulos por fecha

function floobleCalendar() {
// Define Methods
this.setElement = fc_setElement;
this.setElements = fc_setElements;
this.parseDate = fc_parseDate;
this.generateHTML = fc_generateHTML;
this.show = fc_show;
this.hide = fc_hide;
this.moveMonth = fc_moveMonth;
this.setDate = fc_setDate;
this.formatDate = fc_formatDate;
this.setDateFields = fc_setDateFields;
this.parseDateFields = fc_parseDateFields;

this.shown = false;
}

function fc_setElement(formElement) {
this.element = formElement;
this.format = this.element.title;
this.value = this.element.value;
this.id = this.element.id;
this.mode = 1;
}

function fc_setElements(monthElement, dayElement, yearElement) {
this.mElement = monthElement;
this.dElement = dayElement;
this.yElement = yearElement;
this.id = this.mElement.id + '-' + this.dElement.id + '-' + this.yElement.id;
this.element = this.mElement;
if (fc_absoluteOffsetLeft(this.dElement) < fc_absoluteOffsetLeft(this.element)) {
this.element = this.dElement;
}
if (fc_absoluteOffsetLeft(this.yElement) < fc_absoluteOffsetLeft(this.element)) {
this.element = this.yElement;
}
if (fc_absoluteOffsetTop(this.mElement) > fc_absoluteOffsetTop(this.element)) {
this.element = this.mElement;
}
if (fc_absoluteOffsetTop(this.dElement) > fc_absoluteOffsetTop(this.element)) {
this.element = this.dElement;
}
if (fc_absoluteOffsetTop(this.yElement) > fc_absoluteOffsetTop(this.element)) {
this.element = this.yElement;
}

this.mode = 2;
}

function fc_parseDate() {
if (this.element.value) {
this.date = new Date();
var out = '';
var token = '';
var lastCh, ch;
var start = 0;
lastCh = this.format.substring(0, 1);
for (i = 0; i < this.format.length; i++) {
ch = this.format.substring(i, i+1);
if (ch == lastCh) {
token += ch;
} else {
fc_parseToken(this.date, token, this.element.value, start);
start += token.length;
token = ch;
}
lastCh = ch;
}
fc_parseToken(this.date, token, this.element.value, start);
} else {
this.date = new Date();
}
if ('' + this.date.getMonth() == 'NaN') {
this.date = new Date();
}
}

function fc_parseDateFields() {
this.date = new Date();
if (this.mElement.value) this.date.setMonth(fc_getFieldValue(this.mElement) - 1);
if (this.dElement.value) this.date.setDate(fc_getFieldValue(this.dElement)) ;
if (this.yElement.value) this.date.setFullYear(fc_getFieldValue(this.yEleme nt));
if ('' + this.date.getMonth() == 'NaN') {
this.date = new Date();
}
}

function fc_setDate(d, m, y) {
this.date.setYear(y);
this.date.setMonth(m);
this.date.setDate(d);
if (this.mode == 1) {
this.element.value = this.formatDate();
} else {
this.setDateFields();
}
this.hide();
}

function fc_setDateFields() {
fc_setFieldValue(this.mElement, fc_zeroPad(this.date.getMonth() + 1));
fc_setFieldValue(this.dElement, fc_zeroPad(this.date.getDate()));
fc_setFieldValue(this.yElement, this.date.getFullYear());
}

function fc_formatDate() {
var out = '';
var token = '';
var lastCh, ch;
lastCh = this.format.substring(0, 1);
for (i = 0; i < this.format.length; i++) {
ch = this.format.substring(i, i+1);
if (ch == lastCh) {
token += ch;
} else {
out += fc_formatToken(this.date, token);
token = ch;
}
lastCh = ch;
}
out += fc_formatToken(this.date, token);
return out;
}

function fc_show() {
if (typeof(fc_openCal) != 'undefined') { fc_openCal.hide(); }

if (this.mode == 1) {
this.parseDate();
} else {
this.parseDateFields();
}
this.showDate = new Date(this.date.getTime());
if (typeof(this.div) != 'undefined') {
this.div.innerHTML = this.generateHTML();
}

if (typeof(this.div) == 'undefined') {
this.div = document.createElement('DIV');
this.div.style.position = 'absolute';
this.div.style.display = 'none';
this.div.className = 'fc_main';
this.div.innerHTML = this.generateHTML();
this.div.style.left = fc_absoluteOffsetLeft(this.element);
this.div.style.top = fc_absoluteOffsetTop(this.element) + this.element.offsetHeight + 1;
document.body.appendChild(this.div);
}
this.div.style.display = 'block';
this.shown = true;
fc_openCal = this;
}

function fc_generateHTML() {
var html = '<TABLE><TR><TD CLASS="fc_head" COLSPAN="6"><DIV STYLE="float: right"><a class="fc_head" href="http://www.flooble.com/scripts/calendar.php" target="_blank">©</a></DIV>CALENDAR:</TD><TD CLASS="fc_date" onMouseover="this.className = \'fc_dateHover\';" onMouseout="this.className=\'fc_date\';" onClick="getCalendar(\'' + this.id + '\').hide();"><B>X</B></TD></TR>';
html += '<TR><TD CLASS="fc_date" onMouseover="this.className = \'fc_dateHover\';" onMouseout="this.className=\'fc_date\';" onClick="getCalendar(\'' + this.id + '\').moveMonth(-12);"><B><<</B></TD><TD CLASS="fc_date" onMouseover="this.className = \'fc_dateHover\';" onMouseout="this.className=\'fc_date\';" onClick="getCalendar(\'' + this.id + '\').moveMonth(-1);"><B><</B></TD><TD COLSPAN="3" CLASS="fc_wk">' + fc_months[this.showDate.getMonth()] + ' ' + fc_getYear(this.showDate) + '</TD><TD CLASS="fc_date" onMouseover="this.className = \'fc_dateHover\';" onMouseout="this.className=\'fc_date\';" onClick="getCalendar(\'' + this.id + '\').moveMonth(1);"><B>></B></TD><TD CLASS="fc_date" onMouseover="this.className = \'fc_dateHover\';" onMouseout="this.className=\'fc_date\';" onClick="getCalendar(\'' + this.id + '\').moveMonth(12);"><B>>></B></TD></TR>';
html += '<TR><TD WIDTH="14%" CLASS="fc_wk">Mo</TD><TD WIDTH="14%" CLASS="fc_wk">Tu</TD><TD WIDTH="14%" CLASS="fc_wk">We</TD><TD WIDTH="14%" CLASS="fc_wk">Th</TD><TD WIDTH="14%" CLASS="fc_wk">Fr</TD><TD class="fc_wknd" WIDTH="14%">Sa</TD><TD class="fc_wknd" WIDTH="14%">Su</TD></TR>';
html += '<TR>';
var dow = 0;
var i, style;
var totald = fc_monthLength(this.showDate);
for (i = 0; i < fc_firstDOW(this.showDate); i++) {
dow++;
html += '<TD> </TD>';
}
for (i = 1; i <= totald; i++) {
if (dow == 0) { html += '<TR>'; }
if (this.showDate.getMonth() == this.date.getMonth() && this.showDate.getYear() == this.date.getYear() && this.date.getDate() == i) {
style = ' style="font-weight: bold;"';
} else {
style = '';
}
html += '<TD CLASS="fc_date" onMouseover="this.className = \'fc_dateHover\';" onMouseout="this.className=\'fc_date\';" onClick="getCalendar(\'' + this.id + '\').setDate(' + i + ', ' + this.showDate.getMonth() + ', ' + this.showDate.getFullYear() + ');" ' + style + '>' + i + '</TD>';
dow++;
if (dow == 7) {
html += '</TR>';
dow = 0;
}
}
if (dow != 0) {
for (i = dow; i < 7; i++) {
html += '<TD> </TD>';
}
}
html +='</TR>';
html += '</TABLE>';
return html;
}

function fc_hide() {
if (this.div != false) {
this.div.style.display = 'none';
}
this.shown = false;
fc_openCal = undefined;
}

function fc_moveMonth(amount) {
var m = this.showDate.getMonth();
var y = fc_getYear(this.showDate);
if (amount == 1) {
if (m == 11) {
this.showDate.setMonth(0);
this.showDate.setYear(y + 1);
} else {
this.showDate.setMonth(m + 1);
}
} else if (amount == -1) {
if (m == 0) {
this.showDate.setMonth(11);
this.showDate.setYear(y - 1);
} else {
this.showDate.setMonth(m - 1);
}
} else if (amount == 12) {
this.showDate.setYear(y + 1);
} else if (amount == -12) {
this.showDate.setYear(y - 1);
}
this.div.innerHTML = this.generateHTML();
}

//--Utils-------------------------------------------------------------
  #7 (permalink)  
Antiguo 08/10/2008, 10:13
 
Fecha de Ingreso: septiembre-2008
Mensajes: 12
Antigüedad: 15 años, 7 meses
Puntos: 0
Respuesta: Ordenar articulos por fecha

function fc_absoluteOffsetTop(obj) {
var top = obj.offsetTop;
var parent = obj.offsetParent;
while (parent != document.body) {
top += parent.offsetTop;
parent = parent.offsetParent;
}
return top;
}

function fc_absoluteOffsetLeft(obj) {
var left = obj.offsetLeft;
var parent = obj.offsetParent;
while (parent != document.body) {
left += parent.offsetLeft;
parent = parent.offsetParent;
}
return left;
}

function fc_firstDOW(date) {
var dow = date.getDay();
var day = date.getDate();
if (day % 7 == 0) return dow;
return (7 + dow - (day % 7)) % 7;
}

function fc_getYear(date) {
var y = date.getYear();
if (y > 1900) return y;
return 1900 + y;
}

function fc_monthLength(date) {
var month = date.getMonth();
var totald = 30;
if (month == 0
|| month == 2
|| month == 4
|| month == 6
|| month == 7
|| month == 9
|| month == 11) totald = 31;
if (month == 1) {
var year = date.getYear();
if (year % 4 == 0 && (year % 400 == 0 || year % 100 != 0))
totald = 29;
else
totald = 28;
}
return totald;
}

function fc_formatToken(date, token) {
var command = token.substring(0, 1);
if (command == 'y' || command == 'Y') {
if (token.length == 2) { return fc_zeroPad(date.getFullYear() % 100); }
if (token.length == 4) { return date.getFullYear(); }
}
if (command == 'd' || command == 'D') {
if (token.length == 2) { return fc_zeroPad(date.getDate()); }
}
if (command == 'm' || command == 'M') {
if (token.length == 2) { return fc_zeroPad(date.getMonth() + 1); }
if (token.length == 3) { return fc_months[date.getMonth()]; }
}
return token;
}

function fc_parseToken(date, token, value, start) {
var command = token.substring(0, 1);
var v;
if (command == 'y' || command == 'Y') {
if (token.length == 2) {
v = value.substring(start, start + 2);
if (v < 70) { date.setFullYear(2000 + parseInt(v)); } else { date.setFullYear(1900 + parseInt(v)); }
}
if (token.length == 4) { v = value.substring(start, start + 4); date.setFullYear(v);}
}
if (command == 'd' || command == 'D') {
if (token.length == 2) { v = value.substring(start, start + 2); date.setDate(v); }
}
if (command == 'm' || command == 'M') {
if (token.length == 2) { v = value.substring(start, start + 2); date.setMonth(v - 1); }
if (token.length == 3) {
v = value.substring(start, start + 3);
var i;
for (i = 0; i < fc_months.length; i++) {
if (fc_months[i].toUpperCase() == v.toUpperCase()) { date.setMonth(i); }
}
}
}
}

function fc_zeroPad(num) {
if (num < 10) { return '0' + num; }
return num;
}

function fc_getObj(id) {
if (fc_ie) { return document.all[id]; }
else { return document.getElementById(id); }
}

function fc_setFieldValue(field, value) {
if (field.type.substring(0,6) == 'select') {
var i;
for (i = 0; i < field.options.length; i++) {
if (fc_equals(field.options[i].value, value)) {
field.selectedIndex = i;
}
}
} else {
field.value = value;
}
}

function fc_getFieldValue(field) {
if (field.type.substring(0,6) == 'select') {
return field.options[field.selectedIndex].value;
} else {
return field.value;
}
}

function fc_equals(val1, val2) {
if (val1 == val2) return true;
if (1 * val1 == 1 * val2) return true;
return false;
}

</script>

<style>
.fc_main { background: #DDDDDD; border: 1px solid #000000; font-family: Verdana; font-size: 10px; }
.fc_date { border: 1px solid #D9D9D9; cursor:pointer; font-size: 10px; text-align: center;}
.fc_dateHover, TD.fc_date:hover { cursor:pointer; border-top: 1px solid #FFFFFF; border-left: 1px solid #FFFFFF; border-right: 1px solid #999999; border-bottom: 1px solid #999999; background: #E7E7E7; font-size: 10px; text-align: center; }
.fc_wk {font-family: Verdana; font-size: 10px; text-align: center;}
.fc_wknd { color: #FF0000; font-weight: bold; font-size: 10px; text-align: center;}
.fc_head { background: #000066; color: #FFFFFF; font-weight:bold; text-align: left; font-size: 11px; }
</style>
---------------------------FIN CODIGO CALENDARIO--------------

Y el paso dos sería escribir esto en la pagina que quiero mostrar el calendario


<input size="12" id="fc_1223485425" type="text" READONLY name="" title="MMM DD, YYYY" > <input type="button" value="=" onclick="displayCalendarFor('fc_1223485425');">

---------------------------------FIN CODIGO MOSTAR CALENDARIO----------------------

Mi idea es pasar el script a un archivo .js al cual después llamaré desde la página y también tengo pensado crear un archivo .css con el estilo para luego también agregar en la pagina.

Pero lamentablemente no lo puedo hacer funcionar, en pagina que escribo con echo "..."; cambié las comillas dobles " " por simples ' ' pensando que así me iba a funcionar el javascript pero sin embargo no me funciona. Creo que es porque cuando escribo con php, esto: <input size="12" id="fc_1223485425" type="text" READONLY name="" title="MMM DD, YYYY" > <input type="button" value="=" onclick="displayCalendarFor('fc_1223485425');"> todavía no se ha creado el input con id="fc_1223485425" cuando hago click en el botón.

Espero puedan ayudarme !

MUCHAS GRACIAS !
  #8 (permalink)  
Antiguo 08/10/2008, 10:33
 
Fecha de Ingreso: mayo-2006
Ubicación: Bogotá
Mensajes: 2.061
Antigüedad: 18 años
Puntos: 50
Respuesta: Ordenar articulos por fecha

Eso le quedo un reguero que no entendi nada. pongame el link del calendario y miro como es que funciona para orientarlo como implementarlo.
  #9 (permalink)  
Antiguo 08/10/2008, 10:52
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Ordenar articulos por fecha

Tema trasladado a Javascript.
  #10 (permalink)  
Antiguo 08/10/2008, 10:54
 
Fecha de Ingreso: septiembre-2008
Mensajes: 12
Antigüedad: 15 años, 7 meses
Puntos: 0
Respuesta: Ordenar articulos por fecha

Perdón por el lío entonces helacer. Este es el link http://www.flooble.com/scripts/calendar.php?op=get

Una vez dentro de esa pagina tenes que seleccionar Date format: Jan 31, 2005

Gracias !
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 12:35.