Date
The native Date object in javascript leaves a lot to be desired, and while MooTools 1.2 doesn't extend it, the content of this library that does will likely make its way into MooTools in the near future.
Here are the methods that are available in date.js; be sure to check out date.extras.js below, which adds a bit more functionality.
Date.set and Date.get
You can use the set and get methods to set or retrieve most properties of a date. These are: "Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds", "Time", "TimezoneOffset", "Week", "Timezone", "GMTOffset", "Ordinal", "DayOfYear", "LastMonth", "UTCDate", "UTCDay", "UTCFullYear", "AMPM", "UTCHours", "UTCMilliseconds", "UTCMinutes", "UTCMonth", "UTCSeconds". get is not case sensitive, so you can do get('date').
new Date().get('day');

new Date().get('month');

Date.clone
Clones a date returning a copy of it:
var now = new Date(); var nowCopy = now.clone(); console.log(now); console.log(nowCopy); //they are the same

Date.increment
Increments a value in the date. Optional values are "year", "month", "week", "day", "hour", "minute", "second", and "ms".
var now = new Date(); var oneSecondLater = now.clone().increment('second'); var thirtySecondsLater = now.clone().increment('second', 30); console.log(now); console.log(oneSecondLater); console.log(thirtySecondsLater);

var now = new Date(); var nextMonth = now.clone().increment('month'); var twoYears = now.clone().increment('year', 2); console.log(now); console.log(nextMonth); console.log(twoYears);

The default value is a day:
var today = new Date(); var tomorrow = today.clone().increment(); console.log(today); console.log(tomorrow); //with no arguments, increment will move forward a day

Note: this method will account for the various numbers of days in each month and for leap years.
Date.decrement
Same as Date.increment except moving time backwards.
var now = new Date(); var oneSecondBefore = now.clone().decrement('second'); var thirtySecondsBefore = now.clone().decrement('second', 30); console.log(now); console.log(oneSecondBefore); console.log(thirtySecondsBefore);

var now = new Date(); var lastMonth = now.clone().decrement('month'); var twoYearsAgo = now.clone().decrement('year', 2); console.log(now); console.log(lastMonth); console.log(twoYearsAgo);

The default value is a day:
var today = new Date(); var yesterday = today.clone().decrement(); console.log(today); console.log(yesterday); //with no arguments, decrement will move backwards a day

Date.isLeapYear
Returns true or false.
new Date().isLeapYear(); //true if this is a leap year

Date.clearTime
Sets all the time values to zero (12am exactly).
new Date().clearTime();

Date.diff
Compares two dates. If the date passed as an argument is in the future, the value is positive, else negative.
diff takes as its second argument an optional resolution value. Resolution can be "year", "month", "week", "day", "hour", "minute", "second", and "ms". The default is "day".
var now = new Date(); var tomorrow = now.clone().increment(); console.log(now.diff(tomorrow)); /* 1; default resolution is "day" */ console.log(tomorrow.diff(now)); /* -1 */

var now = new Date(); var yearAndAMonthAgo = now.clone().decrement('month', 13); console.log(now.diff(yearAndAMonthAgo)); /* around -390 days, depending on month */ console.log(now.diff(yearAndAMonthAgo, 'year')); /* 1 */ console.log(now.diff(yearAndAMonthAgo, 'month')); /* 13 */

Note: All values are rounded down (so if you compare two dates that are 26 hours apart with a resolution of "day", you'll get one). When comparing years you'll get the numerical difference between the years, meaning that if you compare Jan 08 to Dec 09, which is 23 months, you'll still only get 1 as a result because 09 - 08 is 1.
Date.getTimezone
Returns the time zone string; e.g. "GMT".
new Date().getTimezone();

Date.getGMTOffset
Returns the offset of the time zone from GMT; e.g. "-0800".
new Date().getGMTOffset();

Date.parse
Parses a string, date, or number to a date using predefined regular expressions. date.js comes with only two of these defined (MM/DD/YYYY, where the / can be a period or a dash, and the other parser is exactly like the first except it adds time parsing: MM/DD/YYYY HH:MM[pm|am]). date.extras.js provides many more of these. See below for how to write your own. If the value fails to parse, returns Date with a value of "Invalid Date" (just as if you tried new Date('foo')).
Date.parse("12/31/1999");

Date.parse("12/31/1999 11:59pm");

Date.parse("foo"); //Invalid Date

Date.parse(new Date()); //just returns the value of new Date()

var now = new Date(); Date.parse(now); //just returns now

Note: Date.parse can be executed as a static method on the Date namespace (as above) and it will return a new Date instance with the parsed date to you. Alternatively, if you execute Date.parse on an instance of a date, you'll alter that instance to the parsed value:
var partyTime = new Date(); partyTime.parse("12.31.1999 11:59pm"); console.log(partyTime); /* same as var partyTime = new Date().parse("12.31.1999 11:59pm"); or var partyTime = Date.parse("12.31.1999 11:59pm"); */

Writing your own parsers
You can write your own regular expressions to parse formats you wish to support. To do this, you need to push your parser into the array of parsers that come with date.js. Here's what it looks like:
//this pattern looks for a string beginning with //"tod" or "Tod" and assumes that the user means //"today", and returns the current date Date.$parsePatterns.extend([{ re: /^tod/i, handler: function() { return new Date(); } },{ //this one looks for "tom" or "Tom" //and assumes the user means tomorrow re: /^tom/i, handler: function() { return new Date().increment(); } },{ //"12.31.08", "12-31-08", "12/31/08", "12.31.2008", //"12-31-2008", "12/31/2008" re: /^(\d{1,2})[\.\-\/](\d{1,2})[\.\-\/](\d{2,4})$/, handler: function(bits){ var d = new Date(); d.setYear(bits[3]); d.setMonth(bits[1].toInt() - 1, bits[2].toInt()); return Date.fixY2K(d); } }]);
For each parser you add, you define an object with re and handler. re is the regular expression applied to the date value being parsed. handler receives as its arguments the result of that regular expression and should create a date and return it.
Date.format
Yeah! A date formatter for javascript! It's pretty standard stuff, though it's not as full featured as other languages.
- a - short day ("Mon", "Tue")
- A - full day ("Monday")
- b - short month ("Jan", "Feb")
- B - full month ("Janurary")
- c - the full date to string ("Mon Dec 10 2007 14:35:42 GMT-0800 (Pacific Standard Time)"; same as .toString() method.
- d - the date to two digits (01, 05, etc)
- H - the hour to two digits in military time (24 hr mode) (01, 11, 14, etc)
- I - the hour in 12 hour time (01, 11, 2, etc)
- j - the day of the year to three digits (001 is Jan 1st)
- m - the numerical month to two digits (01 is Jan, 12 is Dec)
- M - the minuts to two digits (01, 40, 59)
- p - 'AM' or 'PM'
- S - the seconds to two digits (01, 40, 59)
- U - the week to two digits (01 is the week of Jan 1, 52 is the week of Dec 31)
- W - not yet supported
- w - the numerical day of the week, one digit (0 is Sunday, 1 is Monday)
- x - returns the format %m/%d/%Y (12/10/2007)
- X - returns %I:%M%p (02:45PM)
- y - the short year (to digits; "07")
- Y - the four digit year
- T - the GMT offset ("-0800")
- Z - the time zone ("GMT")
- % - returns % (example: %y%% = 07%)
- db - "%Y-%m-%d %H:%M:%S"
- compact - "%Y%m%dT%H%M%S"
- iso8601 - "%Y-%m-%dT%H:%M:%S%T"
- rfc822 - "%a, %d %b %Y %H:%M:%S %Z"
- short - "%d %b %H:%M"
- long - "%B %d, %Y %H:%M"
Example:
var today = new Date(); console.log(today.format("%x")); /* 12/31/1999 */ console.log(today.format("%x %X")); /* 12/31/1999 11:59pm */ console.log(today.format("db")); /* 1999-12-31 23:59:59 */

Note: it's a good idea to write parsers for any inputs that you output data in a given format. If you show the user a date format on your page, any inputs on that page that accept dates should be able to parse that format.
cnet-libraries/03-native/00-date.txt · Last modified: 2008/11/17 23:25 by aaron-n