lunes, 22 de septiembre de 2008

MANEJO DE FECHAS EN JAVA SCRIPT parte 2



- ¿Por fin vas a continuar enseñandome sobre el manejo de fechas en JS?


si, si ya se que me tarde un poco pero seguro que esto te gustara

-¿Pues haber porque la verdad ya me acostumbre a manejar las fechas como me habias enseñado?

me alegra mucho eso quiere decir que si le entendiste a la primera parte pero ahora esto que te voy a enseñar es mucho mas facil de manejar, sin embargo en

situaciones que no requieras hacer demasiadas operaciones con tus fechas recomiendo que uses la forma que ya te enseñe, ya que lo que vamos a ver ahora es

una libreria que se llama DateJS y como tal tiene muchas funciones que puede que jamas lleguemos a usar por lo que solamente agregarias peso muerto a tu

sistema, sin embargo es deciciontuya al fin de cuentas.

- ok, ok ya te entendi pero no has echo mas que acrecentar mi curisidad haber dime de una vez ¿que es datejs?

Tranquilo ya te lo habia dicho DateJS es una libreria que permite manipular fechas en Java Script de una manera muy sencilla

- Ahhhh ¿ Y como se usa?

Bueno en realidad es muy facil de utilizar no tiene la gran ciencia, primero debes de bajar el archivo js que se encuentra en la siguiente direccion:
http://code.google.com/p/datejs/downloads/list

- ¿Oye ya me conecte pero ahí hay dos archivos cual descargo?

Ah si mira si eres un poco observador uno es el archivo con extension js y otro tiene la extencion zip, pues bien el primero es la libreria DateJS esta

libreria es tal cual la programaron y se puede utilizar sin ningun problema, sin embargo para acceder a sus metodos se hara en ingles p.e

Date.today().next().friday() esto desde luego no es un gran problema de ninguna manera sin embargo desarrolladores del mundo al ver la gran potencia y

sencillez de esta libreria acomodaron unos archivos complementarios para que fuera posible llamar a los metodos desde nuestro propio lenguaje, todos esos

archivos de idiomas se encuentran en la version full de la libreria es decir el archivo .zip de esta manera se hace posible definiendo primero el idioma a

utilizar, que con esta libreria podamos hacer algo como: Date.hoy().siguiente().viernes(), pero para esto deberas ver especificamente la traduccion de los

metodos a tu idioma, sin embargo yo te recomiendo usar la libreria en su lengua original, es decir el ingles y no creo que encuentras ningun problema al

implementarla.

-Ahhhh oye eso esta interesante pero apesar de tus recomendaciones como que si tengo ganas de probar el paquete de idiomas

jajajaja, claro esa es la actitud no te limites por loque te digan y si tienes tiempo y ganas echale un vistaso.

- claro que lo hare pero sigueme contando ¿como utilizo esta libreria?

ok, sigo entonces, bueno ahora que ya tienes conocimiento del paquete de idiomas y como te veo con ganas de probarlo te mostrare como hacerle:

* primero buscas en los archivos el nombre valga la redundancia del archivo que corresponda a tu idioma.
* despues de localizarlo debes de hacer algo como las siguientes declaraciones:
en-US [English (United States)]


en-US [English (United States)]


de-DE [German (Germany)]


fr-FR [French (France)]


- Ahhhh creo que si te entiendo, oye pero en caso de que quiera dejarlo con el idioma por defecto ¿ como le hago?
Ahhh oki pues eso es mucho mas facil, simplemente quita la linea de idioma y deja la linea donde agregas el script de JS, el nombre del script claro esta es

el nombre del script por defecto que descargaste, para que me entiendas lo unico que debes de hacer es agregar la siguiente linea:



y simplemente con esto ya podras comenzar a utilizar los metodos de esta libreria, aunque es obvio no esta de mas comentar que es preferible que esta linea

se declare en la cabecera del documento html, php, etc y dicha declaracion debera de ir en cada una de las paginas donde requieras utilizar esta libreria.


- oki, hasta aqui todo claro como el agua del mar muerto, pero sigue por favor que esto cada vez se pone mas interesante

Bene, bene si estas tan ansioso por seguir aprendiendo entonces entremos a la parte medular del asunto.
Aqui unos ejemplos de como usar las sentencias:

// La fecha de hoy
Date.today();

// Agregarle 5 dias a la fecha actual
Date.today().add(5).days();

// Establecer el viernes de esta semana
Date.friday();

// Poner en marzo de este año
Date.march();

// Hoy es viernes?
Date.today().is().friday(); // regresa true|false

// Que dia es hoy?
Date.today().getDayName();

// ¿Qué fecha es el próximo jueves?
Date.today().next().thursday();

// Añadir 3 días a la fecha de hoy
Date.today().add(3).days();

// Hace tres días
(3).days().ago();

// Dentro de 6 meses
var n = 6;
n.months().fromNow();

// Ponerlo a las 8:30 AM del día 15 de este mes
Date.today().set({ day: 15, hour: 8, mintue: 30 });

// Convertir un texto a una fecha
Date.parse(‘today’);
Date.parse(‘t + 5 d’); // hoy + 5 días
Date.parse(‘next thursday’);
Date.parse(‘February 20th 1973);
Date.parse(‘Thu, 1 July 2004 22:30:00);



- Ah orale esto esta interesante, creo que vamos por buen camino esta muy facil asi que no te detengas y enseñame mas

Calma, calma dame un respirito jejejeje, Ahhhhhhh
Bien continuemos, aqui mas ejemplos de lo que podemos hacer con esta libreria, ya que los acoples a lo que necesitas dependera de ti :)
Poner la fecha del primer lunes del año
Date.january().first().monday()


Poner la fecha del ultimo viernes del año
Date.dec().final().friday()

Pon atencion por que el siguiente ejemplo es un poco complicado:
- Ok listo dispara!!!!
jejeje ya voy :)

Poner en el objeto como fecha el 15 del presente mes con una hora de 4:30, posteriormente sumarle 90 dias y asegurarnos que el dia sea un fin de semana, si

no movernos al siguiente fin de semana.

var d1 = Date.today() // creando variable tipo date
.set({ day: 15, hour: 16, minute: 30 }) //estableciendo fecha y hora
.add({ days: 90 })// aumentar 90 dias a la fecha actual
if (!d1.isWeekday()) {
d1.next().monday();
}


- Ahhh que interesante esta heramienta si es buena

Si y toda via falta un poco mas, ya que tambien podemos pasar cadenas de texto como parametro y la libreria interpretara la cadena

-mmmm no te entiendo muy bien
ok, mejor mira estos ejemplos y seguramente entenderas a lo que me refiero



Date.parse(‘today’);


Date.parse(‘tomorrow’);


Date.parse(‘July 8');


Date.parse(‘July 8th, 2007');


Date.parse(‘July 8th, 2007, 10:30 PM’);

Si es un dia diferente al lunes irnos al ultimo lunes
var d1 = Date.parse(‘8-Jul-2007');
if (!d1.is().monday()) {
d1.last().monday();
}
alert(d1.toString(‘dddd, MMMM d, yyyy’));

- Oye que padre creo que ahora si estoy listo para utilizar esta libreria
Me alegro mucho y ya no queda mas que te pongas a trabajar para que le agarres el truco, antes de irme aqui te dejo un poco mas de informacion que te puede ser util:

// avanzar 3 dias apartir de hoy
(3).days().fromNow();

// retorceder 6 meses
(6).months().ago();

// 12 semanas apartir de hoy
var n = 12;
n.weeks().fromNow();

// Avanzar 30 dias apartir de una fecha dada
var d1 = Date.parse(‘07.15.2007');
var d2 = (30).days().after(d1);

mas ejemplos:

Date.today() // Returns today's date, with time set to 00:00 (start of day).

Date.today().next().friday() // Returns the date of the next Friday.
Date.today().last().monday() // Returns the date of the previous Monday.

new Date().next().march() // Returns the date of the next March.
new Date().last().week() // Returns the date one week ago.

Date.today().is().friday() // Returns true|false if the day-of-week matches.
Date.today().is().fri() // Abbreviated day names.

Date.today().is().november() // Month names.
Date.today().is().nov() // Abbreviated month names.

Date.today().is().weekday() // Is today a weekday?

Date.today().addDays(1) // Add one day (+1).
Date.today().addMonths(-3) // Subtract three months (-3).

Date.today().add(1).day() // Add one (+1) day. Supports all date parts (year, month, day, hour, minute, second, millisecond, and weeks)
Date.today().add(-3).months() // Subtract three (-3) months.

(1).day().fromNow() // One (1) day from now.
(3).months().ago() // Three (3) months ago.

var n = 6;
n.months().fromNow() // Six (6) months from now.

Date.monday() // Returns Monday of the current week.
Date.mon() // Abbreviated version of Date.monday()

Date.march() // Returns March 1st of this year.
Date.mar() // Abbreviated version of Date.march()

Date.today().first().thursday() // Returns the first Thursday of the current month.
Date.today().second().thursday()// Returns the second Thursday of the current month.

Date.march().third().thursday() // Returns the third Thursday in March of the current year.
Date.october().fourth().sunday()// Returns the fourth Sunday in October.

Date.today().fifth().sunday() // Returns the fifth Sunday in the current month, or throws a RangeError exception if there are not 5 Sundays in the current

month.
Date.october().final().sunday() // Returns the final Sunday in October.

Date.january().first().monday() // Returns the first Monday of the current year.
Date.december().final().friday()// Returns the last Friday of the current year.

Date.today().at("6:15pm"); // Returns todays date at 6:15pm.

var time = {hour:18, minute:15};
Date.today().at(time); // Set time with a config object.

var birthDayParty = {month: 1, day: 20, hour: 20, minute: 30};
Date.today().set(birthDayParty);// Set date and time with a config object.

CADENAS QUE PUEDEN SER INTERPRETADAS COMO FECHAS

Date.parse('t') // Returns today's date.
Date.parse('today') // Returns today's date.
Date.parse('tomorrow') // Returns tomorrow's date.
Date.parse('yesterday') // Returns yesterday's date.

Date.parse('next friday') // Returns the date of the next Friday.
Date.parse('last monday') // Returns the date of the previous Monday.

Date.parse('July 8th, 2004') // Thu Jul 08 2004
Date.parse('15-Jan-2004') // Thu Jan 15 2004

Date.parse('7/1/2004') // Thu Jul 01 2004
Date.parse('7.1.2004') // Thu Jul 01 2004
Date.parse('07.15.04') // Thu Jul 15 2004

Date.parse('July 23rd 2004') // Fri Jul 23 2004
Date.parse('Sat July 3, 2004') // Sat Jul 03 2004

Date.parse('10:30 PM EST') // Wed Oct 31 2007 20:30:00
Date.parse('10PM') // Wed Oct 31 2007 22:00:00

Date.parse('t + 5d') // Adds 5 days to today.
Date.parse('today - 1 month') // Subtracts 1 month from today.

Date.parse('+') // Add 1 day to today = tomorrow.
Date.parse('- 3months') // Subtract 3 months.

Date.parse('+1year') // Add a year to today.
Date.parse('-12 months') // Subtract 12 months (1 year) from today.

Date.parse('July 4th') // July 4th of this year.
Date.parse('15') // 15th day of current month/year.

Date.parse('July 8th, 2004, 10:30 PM') // Thu Jul 08 2004 22:30:00
Date.parse('2004-07-15T06:45:00') // Thu Jul 15 2004 06:45:00
Date.parse('Thu, 1 July 2004 22:30:00 GMT') // Thu Jul 01 2004 16:30:00

Date.parse('1997-07-16T19:20:15') // ISO 8601 Formats
Date.parse('1997-07-16T19:20:30+01:00') // ISO 8601 with Timezone offset
Date.parse('1985-04-12T23:20:50Z') // RFC 3339 Formats

METODOS DE CAMBIO DE INFORMACION

Date.today().add({ months: 1, days: 5 }).is().fri() // Add 1 month and 5 days, then check if that date is a Friday.

Date.parse('10-July-2004').next().friday().add(-1).month() // Take in a date, then move to the next Friday and subtract a month.

METODOS DE COMPARACION

Date.today().equals( Date.parse('today')) // true|false
Date.parse('last Tues').equals(Date.today()) // true|false

Date.equals(Date.today(), Date.parse('today')) // true|false
Date.compare(Date.today(), Date.parse('today')) // 1 = greater, -1 = less than,

Date.today().compareTo(Date.parse('yesterday')) // 1 = greater, -1 = less than, 0 = equal
Date.today().between(startDate, endDate) // true|false

FORMATO EN FECHAS
new Date().toString() // "Wed Oct 31 2007 16:18:10 GMT-0700 (Pacfic Daylight Time)"
new Date().toString('M/d/yyyy') // "10/31/2007"

Date.today().toString('d-MMM-yyyy') // "31-Oct-2007"
new Date().toString('HH:mm') // "16:18"

Date.today().toString('MMMM dS, yyyy') // "April 12th, 2008"

Date.today().toShortDateString() // "10/31/2007". Culture specific as per Date.CultureInfo.shortDatePattern.
Date.today().toLongDateString() // "Wednesday, October 31, 2007". Culture specific as per Date.CultureInfo.longDatePattern.

new Date().toShortTimeString() // "4:18 PM". Culture specific as per Date.CultureInfo.shortTimePattern.
new Date().toLongTimeString() // "4:18:34 PM". Culture specific as per Date.CultureInfo.longTimePattern.

OTROS METODOS

Date.today().set({ day: 15 }) // Sets the day to the 15th of the current month and year. Other object values include

year|month|day|hour|minute|second.

Date.today().set({ year: 2007, month: 1, day: 20 })


Date.today().add({ days: 2 }) // Adds 2 days to the Date. Other object values include year|month|day|hour|minute|second.

Date.today().add({ years: -1, months: 6, hours: 3 })


Date.today().addYears(1) // Add 1 year.
Date.today().addMonths(-2) // Subtract 2 months.
Date.today().addWeeks(1) // Add 1 week
Date.today().addHours(6) // Add 6 hours.
Date.today().addMinutes(-30) // Subtract 30 minutes
Date.today().addSeconds(15) // Add 15 seconds.
Date.today().addMilliseconds(200) // Add 200 milliseconds.

Date.today().moveToFirstDayOfMonth() // Returns the first day of the current month.
Date.today().moveToLastDayOfMonth() // Returns the last day of the current month.

new Date().clearTime() // Sets the time to 00:00 (start of the day).
Date.today().setTimeToNow() // Resets the time to the current time (now). The functional opposite of .clearTime()
Date.getMonthNumberFromName('March') // 2 - CultureInfo specific.
Date.getDayNumberFromName('sat') // 6 - CultureInfo specific.

Date.isLeapYear(2008) // true|false.
Date.getDaysInMonth(2007, 9) // 31

Date.today().getWeek() // Returns week of year. Returns 1 to (52 | 53) depending on the year
Date.today().setWeek(1) // Sets the week of the year to the Monday of the week set.

var test = new Date(); // Do something... like run a test...
test.getElapsed() // Returns millisecond difference from now.

Date.today().isDaylightSavingTime() // true|false. Is within the Daylight Saving Time.
Date.today().hasDaylightSavingTime() // true|false. Is Daylight Saving Time observed.

fuentes:
http://code.google.com/p/datejs/
http://www.datejs.com/2007/11/27/getting-started-with-datejs/

Sale pues ahora si me voy espero que te sirva de algo todo esto
-seguro que si
Oras cuidate y hasta la proxima

No hay comentarios: