This date class adapted from http://code.google.com/p/flexible-js-formatting/.
The date parsing and format syntax is a subset of PHP’s date(http://www.php.net/date) function, and the formats that are supported will provide results equivalent to their PHP versions.
Sample date:
'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
Format Output Description
------ ---------- --------------------------------------------------------------
d 10 Day of the month, 2 digits with leading zeros
D Wed A textual representation of a day, three letters
j 10 Day of the month without leading zeros
l Wednesday A full textual representation of the day of the week
S th English ordinal day of month suffix, 2 chars (use with j)
w 3 Numeric representation of the day of the week
z 9 The julian date, or day of the year (0-365)
W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
F January A full textual representation of the month
m 01 Numeric representation of a month, with leading zeros
M Jan Month name abbreviation, three letters
n 1 Numeric representation of a month, without leading zeros
t 31 Number of days in the given month
L 0 Whether it's a leap year (1 if it is a leap year, else 0)
Y 2007 A full numeric representation of a year, 4 digits
y 07 A two digit representation of a year
a pm Lowercase Ante meridiem and Post meridiem
A PM Uppercase Ante meridiem and Post meridiem
g 3 12-hour format of an hour without leading zeros
G 15 24-hour format of an hour without leading zeros
h 03 12-hour format of an hour with leading zeros
H 15 24-hour format of an hour with leading zeros
i 05 Minutes with leading zeros
s 01 Seconds, with leading zeros
u 001 to 999 Milliseconds, with leading zeros
O -0600 Difference to Greenwich time (GMT) in hours
o -06:00 Difference to Greenwich time (GMT) in hours:minutes
T CST Timezone setting of the machine running the code
Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
Myna.println(dt.format('Y-m-d')); //2007-01-10
Myna.println(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
Myna.println(dt.format('l, \\t\\he dS of F Y h:i:s A')); //Wednesday, the 10th of January 2007 03:05:01 PM
Here are some standard date/time patterns that you might find helpful. They are not part of the source of Date.js, but to use them you can simply copy this block of code into any script that is included after Date.js and they will also become globally available on the Date object. Feel free to add or remove patterns as needed in your code.
Date.patterns = {
ISO8601Long:"Y-m-d H:i:s",
ISO8601Short:"Y-m-d",
ShortDate: "n/j/Y",
LongDate: "l, F d, Y",
FullDateTime: "l, F d, Y g:i:s A",
MonthDay: "F d",
ShortTime: "g:i A",
LongTime: "g:i:s A",
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
YearMonth: "F, Y"
};
var dt = new Date();
Myna.println(dt.format(Date.patterns.ShortDate));
Date | This date class adapted from http://code.google.com/p/flexible-js-formatting/. |
Functions | |
format | Formats a date given the supplied format string format - {String}The format string |
parseDate | Parses the passed string using the specified format. |
getTimezone | Get the timezone abbreviation of the current date (equivalent to the format specifier ‘T’). |
getGMTOffset | Get the offset from GMT of the current date (equivalent to the format specifier ‘O’). |
getDayOfYear | Get the numeric day number of the year, adjusted for leap year. |
getWeekOfYear | Get the string representation of the numeric week number of the year (equivalent to the format specifier ‘W’). |
getFirstDayOfMonth | Get the first day of the current month, adjusted for leap year. |
getLastDayOfMonth | Get the last day of the current month, adjusted for leap year. |
getDaysInMonth | Get the number of days in the current month, adjusted for leap year. |
getSuffix | Get the English ordinal suffix of the current day (equivalent to the format specifier ‘S’). |
clone | Creates and returns a new Date instance with the exact same date value as the called instance. |
clearTime | Clears any time information from this date clone - {Boolean}true to create a clone of this date, clear the time and return it |
add | Provides a convenient method of performing basic date arithmetic. |
diff | returns returns the time between two date objects |
getInterval | returns a time interval in milliseconds. |
parseInterval | returns an object with a breakdown of the units in an interval |
formatInterval | returns an interval in milliseconds as human readable string. |
monthsBetween | [static] returns the number of whole calendar months between two dates |
Date.prototype.format =Date.prototype.dateFormat Date.createNewFormat = function( format )
Formats a date given the supplied format string format - {String}The format string
{String} The formatted date @method
Date.parseDate = function( input, format )
Parses the passed string using the specified format. Note that this function expects dates in normal calendar format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of the date format that is not specified will default to the current date value for that part. Time parts can also be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format string or the parse operation will fail. Example Usage:
//dt = Fri May 25 2007 (current date)
var dt = new Date();
//dt = Thu May 25 2006 (today's month/day in 2006)
dt = Date.parseDate("2006", "Y");
//dt = Sun Jan 15 2006 (all date parts specified)
dt = Date.parseDate("2006-1-15", "Y-m-d");
//dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
input | {String}The unparsed date as a string |
format | {String}The format the date is in |
{Date} The parsed date @static
Date.prototype.getTimezone = function()
Get the timezone abbreviation of the current date (equivalent to the format specifier ‘T’).
{String} The abbreviated timezone name (e.g. ‘CST’)
Date.prototype.getGMTOffset = function()
Get the offset from GMT of the current date (equivalent to the format specifier ‘O’).
{String} The 4-character offset string prefixed with + or | (e.g. ‘-0600’) |
Date.prototype.getDayOfYear = function()
Get the numeric day number of the year, adjusted for leap year.
{Number} 0 through 364 (365 in leap years)
Date.prototype.getWeekOfYear = function()
Get the string representation of the numeric week number of the year (equivalent to the format specifier ‘W’).
{String} ‘00’ through ‘52’
Date.prototype.getFirstDayOfMonth = function()
Get the first day of the current month, adjusted for leap year. The returned value is the numeric day index within the week (0-6) which can be used in conjunction with the {@link #monthNames} array to retrieve the textual day name. Example:
var dt = new Date('1/10/2007');
Myna.println(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
{Number} The day number (0-6)
Date.prototype.getLastDayOfMonth = function()
Get the last day of the current month, adjusted for leap year. The returned value is the numeric day index within the week (0-6) which can be used in conjunction with the {@link #monthNames} array to retrieve the textual day name. Example:
var dt = new Date('1/10/2007');
Myna.println(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
{Number} The day number (0-6)
Date.prototype.getDaysInMonth = function()
Get the number of days in the current month, adjusted for leap year.
{Number} The number of days in the month
Date.prototype.getSuffix = function()
Get the English ordinal suffix of the current day (equivalent to the format specifier ‘S’).
{String} ‘st, ‘nd’, ‘rd’ or ‘th’
Date.prototype.clone = function()
Creates and returns a new Date instance with the exact same date value as the called instance. Dates are copied and passed by reference, so if a copied date variable is modified later, the original variable will also be changed. When the intention is to create a new variable that will not modify the original instance, you should create a clone.
//wrong way:
var orig = new Date('10/1/2006');
var copy = orig;
copy.setDate(5);
Myna.println(orig); //returns 'Thu Oct 05 2006'!
//correct way:
var orig = new Date('10/1/2006');
var copy = orig.clone();
copy.setDate(5);
Myna.println(orig); //returns 'Thu Oct 01 2006'
{Date} The new Date instance
Date.prototype.clearTime = function( clone )
Clears any time information from this date clone - {Boolean}true to create a clone of this date, clear the time and return it
{Date} this or the clone
Date.prototype.add = function( interval, value )
Provides a convenient method of performing basic date arithmetic. This method does not modify the Date instance being called - it creates and returns a new Date instance containing the resulting date value.
interval | Either a Date Interval Type (see below) or a time in milliseconds to add to this date (see <Date.getInterval>). If this is a negative time, it will be subtracted |
value | Optional default 0 This is only necessary if interval is a Date Interval Type (see below). In that case this the number of units to add. If this is a negative value it will be subtracted |
Date.MILLI | ”ms” |
Date.SECOND | ”s” |
Date.MINUTE | ”mi” |
Date.HOUR | ”h” |
Date.DAY | ”d” |
Date.MONTH | ”mo” |
Date.YEAR | ”y” |
The new Date instance
//Basic usage:
var dt = new Date('10/29/2006').add(Date.DAY, 5);
Myna.println(dt); //returns 'Fri Oct 06 2006 00:00:00'
//can also use string codes:
var dt = new Date('10/29/2006').add("d", 5);
Myna.println(dt); //returns 'Fri Oct 06 2006 00:00:00'
//Or use an interval for applying to multiple dates
var interval = Date.getInterval("d",7) //one week
//add a week to all the dates in the 'preDefinedDates' array
var modifiedDates =preDefinedDates.map(function(date){
return date.add(interval);
})
//Negative values will subtract correctly:
var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
Myna.println(dt2); //returns 'Tue Sep 26 2006 00:00:00'
//You can even chain several calls together in one line!
var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
Myna.println(dt3); //returns 'Fri Oct 06 2006 07:30:00'
Date.diff=function( d1, d2, scale )
returns returns the time between two date objects
d1 | First date if less than d2 result will be positive |
d2 | Second date |
scale | Optional, default Date.MILLI The result will be divided by this interval to produce a result in this scale |
//return the difference in the d1 and d2 to the nearest week
Myna.println("Age: " + Math.round(Date.diff(create_date,new Date(),Date.WEEK)) );
Date.getInterval = function( interval, count )
returns a time interval in milliseconds. This can be used with Date.add instead of specifying the type and length
interval | Either a Date Interval Type (see below) or a time in milliseconds to add to this date (see <Date.getInterval>). If this is a negative time, it will be subtracted |
count | Optional default 1 Number of interval values to return |
Date.MILLI | ”ms” |
Date.SECOND | ”s” |
Date.MINUTE | ”mi” |
Date.HOUR | ”h” |
Date.DAY | ”d” |
Date.MONTH | ”mo” |
Date.YEAR | ”y” |
var interval = Date.getInterval("d",7) //one week
//add a week to all the dates in the 'preDefinedDates' array
var modifiedDates = preDefinedDates.map(function(date){
return date.add(interval);
})
Date.parseInterval = function( interval )
returns an object with a breakdown of the units in an interval
interval | an interval in milliseconds to format |
Date.formatInterval = function( interval, options )
returns an interval in milliseconds as human readable string.
interval | an interval in milliseconds to format |
options | formating options, see Options below |
precision | Optional, default Date.MILLI Level of precision to use. This defines the smallest unit to be returned |
scale | Optional, default null Integer. If defined, this is the number of places from the left to return. This will ignore empty places if removeEmpty is true |
removeEmpty | Optional, default true Boolean. if true, 0 valuse will be stripped from the result. |
sep | Optional, default ‘, ‘ String. Separator to use between time parts |
style | Optional, default ‘long’ Output style. See Styles below |
long | Example: 1 year, 1 week, 4 days, 10 hours, 8 minutes, 3 seconds, 667 milliseconds |
short | Example: 1y, 1w, 4d, 10h, 8m, 31s, 125ms |
none | Example: 1, 1, 4, 10, 9, 1, 642 |
var interval = new Date().getTime() - new Date().add(Date.DAY,-376).clearTime()
Myna.println(Date.formatInterval(interval))
//prints: 1 year, 1 week, 4 days, 10 hours, 11 minutes, 17 seconds, 332 milliseconds
Myna.println(Date.formatInterval(interval,{
precision: Date.SECOND,
scale:2,
removeEmpty:false,
sep:":",
style:"none"
}))
//prints (year:weeks): 1:1
Formats a date given the supplied format string format - {String}The format string
Date.prototype.format =Date.prototype.dateFormat Date.createNewFormat = function( format )
Parses the passed string using the specified format.
Date.parseDate = function( input, format )
Get the timezone abbreviation of the current date (equivalent to the format specifier ‘T’).
Date.prototype.getTimezone = function()
Get the offset from GMT of the current date (equivalent to the format specifier ‘O’).
Date.prototype.getGMTOffset = function()
Get the numeric day number of the year, adjusted for leap year.
Date.prototype.getDayOfYear = function()
Get the string representation of the numeric week number of the year (equivalent to the format specifier ‘W’).
Date.prototype.getWeekOfYear = function()
Get the first day of the current month, adjusted for leap year.
Date.prototype.getFirstDayOfMonth = function()
Get the last day of the current month, adjusted for leap year.
Date.prototype.getLastDayOfMonth = function()
Get the number of days in the current month, adjusted for leap year.
Date.prototype.getDaysInMonth = function()
Get the English ordinal suffix of the current day (equivalent to the format specifier ‘S’).
Date.prototype.getSuffix = function()
Creates and returns a new Date instance with the exact same date value as the called instance.
Date.prototype.clone = function()
Clears any time information from this date clone - {Boolean}true to create a clone of this date, clear the time and return it
Date.prototype.clearTime = function( clone )
Provides a convenient method of performing basic date arithmetic.
Date.prototype.add = function( interval, value )
returns returns the time between two date objects
Date.diff=function( d1, d2, scale )
returns a time interval in milliseconds.
Date.getInterval = function( interval, count )
returns an object with a breakdown of the units in an interval
Date.parseInterval = function( interval )
returns an interval in milliseconds as human readable string.
Date.formatInterval = function( interval, options )
[static] returns the number of whole calendar months between two dates
Date.monthsBetween = function( d1, d2 )