Date

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.

Following is the list of all currently supported formats

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)

Example usage (note that you must escape format specifiers with ‘\\’ to render them as character literals)

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"
};

Example usage

var dt = new Date();
Myna.println(dt.format(Date.patterns.ShortDate));
Summary
DateThis date class adapted from http://code.google.com/p/flexible-js-formatting/.
Functions
formatFormats a date given the supplied format string format - {String}The format string
parseDateParses the passed string using the specified format.
getTimezoneGet the timezone abbreviation of the current date (equivalent to the format specifier ‘T’).
getGMTOffsetGet the offset from GMT of the current date (equivalent to the format specifier ‘O’).
getDayOfYearGet the numeric day number of the year, adjusted for leap year.
getWeekOfYearGet the string representation of the numeric week number of the year (equivalent to the format specifier ‘W’).
getFirstDayOfMonthGet the first day of the current month, adjusted for leap year.
getLastDayOfMonthGet the last day of the current month, adjusted for leap year.
getDaysInMonthGet the number of days in the current month, adjusted for leap year.
getSuffixGet the English ordinal suffix of the current day (equivalent to the format specifier ‘S’).
cloneCreates and returns a new Date instance with the exact same date value as the called instance.
clearTimeClears any time information from this date clone - {Boolean}true to create a clone of this date, clear the time and return it
addProvides a convenient method of performing basic date arithmetic.
diffreturns returns the time between two date objects
getIntervalreturns a time interval in milliseconds.
parseIntervalreturns an object with a breakdown of the units in an interval
formatIntervalreturns an interval in milliseconds as human readable string.
monthsBetween[static] returns the number of whole calendar months between two dates

Functions

format

Date.prototype.format =Date.prototype.dateFormat Date.createNewFormat = function(
   format
)

Formats a date given the supplied format string format - {String}The format string

Returns

{String} The formatted date @method

parseDate

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

Returns

{Date} The parsed date @static

getTimezone

Date.prototype.getTimezone = function()

Get the timezone abbreviation of the current date (equivalent to the format specifier ‘T’).

Returns

{String} The abbreviated timezone name (e.g.  ‘CST’)

getGMTOffset

Date.prototype.getGMTOffset = function()

Get the offset from GMT of the current date (equivalent to the format specifier ‘O’).

Returns

{String} The 4-character offset string prefixed with + or(e.g.  ‘-0600’)

getDayOfYear

Date.prototype.getDayOfYear = function()

Get the numeric day number of the year, adjusted for leap year.

Returns

{Number} 0 through 364 (365 in leap years)

getWeekOfYear

Date.prototype.getWeekOfYear = function()

Get the string representation of the numeric week number of the year (equivalent to the format specifier ‘W’).

Returns

{String} ‘00’ through ‘52’

getFirstDayOfMonth

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'

Returns

{Number} The day number (0-6)

getLastDayOfMonth

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'

Returns

{Number} The day number (0-6)

getDaysInMonth

Date.prototype.getDaysInMonth = function()

Get the number of days in the current month, adjusted for leap year.

Returns

{Number} The number of days in the month

getSuffix

Date.prototype.getSuffix = function()

Get the English ordinal suffix of the current day (equivalent to the format specifier ‘S’).

Returns

{String} ‘st, ‘nd’, ‘rd’ or ‘th’

clone

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.

Example of correctly cloning a date

//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'

Returns

{Date} The new Date instance

clearTime

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

Returns

{Date} this or the clone

add

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.

Parameters

intervalEither 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
valueOptional 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 Interval Types

Date.MILLI”ms”
Date.SECOND”s”
Date.MINUTE”mi”
Date.HOUR”h”
Date.DAY”d”
Date.MONTH”mo”
Date.YEAR”y”

Returns

The new Date instance

Examples

//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'

diff

Date.diff=function(d1,
d2,
scale)

returns returns the time between two date objects

Parameters

d1First date if less than d2 result will be positive
d2Second date
scaleOptional, default Date.MILLI The result will be divided by this interval to produce a result in this scale

Example

//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)) );

getInterval

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

Parameters

intervalEither 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
countOptional default 1 Number of interval values to return

Date Interval Types

Date.MILLI”ms”
Date.SECOND”s”
Date.MINUTE”mi”
Date.HOUR”h”
Date.DAY”d”
Date.MONTH”mo”
Date.YEAR”y”

Note

  • Date.MONTH is always 30 days
  • Date.YEAR is always 365 days

Example

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);
})

parseInterval

Date.parseInterval = function(interval)

returns an object with a breakdown of the units in an interval

Parameters

intervalan interval in milliseconds to format

returned object properties

  • milliSeconds
  • seconds
  • minutes
  • hours
  • days
  • weeks
  • years

formatInterval

Date.formatInterval = function(interval,
options)

returns an interval in milliseconds as human readable string.

Parameters

intervalan interval in milliseconds to format
optionsformating options, see Options below

Options

precisionOptional, default Date.MILLI Level of precision to use.  This defines the smallest unit to be returned
scaleOptional, 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
removeEmptyOptional, default true Boolean. if true, 0 valuse will be stripped from the result.
sepOptional, default ‘, ‘ String.  Separator to use between time parts
styleOptional, default ‘long’ Output style.  See Styles below

Styles

longExample: 1 year, 1 week, 4 days, 10 hours, 8 minutes, 3 seconds, 667 milliseconds
shortExample: 1y, 1w, 4d, 10h, 8m, 31s, 125ms
noneExample: 1, 1, 4, 10, 9, 1, 642

Example

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

monthsBetween

Date.monthsBetween = function(d1,
d2)

[static] returns the number of whole calendar months between two dates

Parameters

d1first date
d2second date

Note

if d1 > d2 the answer will be negative

Date.prototype.format =Date.prototype.dateFormat Date.createNewFormat = function(
   format
)
Formats a date given the supplied format string format - {String}The format string
Date.parseDate = function(input,
format)
Parses the passed string using the specified format.
Date.prototype.getTimezone = function()
Get the timezone abbreviation of the current date (equivalent to the format specifier ‘T’).
Date.prototype.getGMTOffset = function()
Get the offset from GMT of the current date (equivalent to the format specifier ‘O’).
Date.prototype.getDayOfYear = function()
Get the numeric day number of the year, adjusted for leap year.
Date.prototype.getWeekOfYear = function()
Get the string representation of the numeric week number of the year (equivalent to the format specifier ‘W’).
Date.prototype.getFirstDayOfMonth = function()
Get the first day of the current month, adjusted for leap year.
Date.prototype.getLastDayOfMonth = function()
Get the last day of the current month, adjusted for leap year.
Date.prototype.getDaysInMonth = function()
Get the number of days in the current month, adjusted for leap year.
Date.prototype.getSuffix = function()
Get the English ordinal suffix of the current day (equivalent to the format specifier ‘S’).
Date.prototype.clone = function()
Creates and returns a new Date instance with the exact same date value as the called 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.prototype.add = function(interval,
value)
Provides a convenient method of performing basic date arithmetic.
Date.diff=function(d1,
d2,
scale)
returns returns the time between two date objects
Date.getInterval = function(interval,
count)
returns a time interval in milliseconds.
Date.parseInterval = function(interval)
returns an object with a breakdown of the units in an interval
Date.formatInterval = function(interval,
options)
returns an interval in milliseconds as human readable string.
Date.monthsBetween = function(d1,
d2)
[static] returns the number of whole calendar months between two dates