Search

1/30/2010

javascript date

Here are some examples of using strings to initialize a date object. It's interesting how many different formats you can use to specify the date.

>>> new Date('2009 11 12')
Thu Nov 12 2009 00:00:00 GMT-0800 (Pacific Standard Time)
>>> new Date('1 1 2012')
Sun Jan 01 2012 00:00:00 GMT-0800 (Pacific Standard Time)
>>> new Date('1 mar 2012 5:30')
Thu Mar 01 2012 05:30:00 GMT-0800 (Pacific Standard Time)

It is good that JavaScript can figure out a date from different strings, but this is not really a reliable way of defining a precise date. The better way is to pass numeric values to the Date() constructor representing:
* Year
* Month: 0 (January) to 11 (December)
* Day: 1 to 31
* Hour: 0 to 23
* Minutes: 0 to 59
* Seconds: 0 to 59
* Milliseconds: 0 to 999

Let's see some examples.
Passing all the parameters:

>>> new Date(2008, 0, 1, 17, 05, 03, 120)
Tue Jan 01 2008 17:05:03 GMT-0800 (Pacific Standard Time)
Passing date and hour:
>>> new Date(2008, 0, 1, 17)
Tue Jan 01 2008 17:00:00 GMT-0800 (Pacific Standard Time)

If you call Date() without new, you get a string representing the current date, whether or not you pass any parameters. This gives the current time (current when this example was run):

>>> Date()
"Thu Jan 17 2008 23:11:32 GMT-0800 (Pacific Standard Time)"
>>> Date(1, 2, 3, "it doesn't matter");
"Thu Jan 17 2008 23:11:35 GMT-0800 (Pacific Standard Time)"

沒有留言: