Function Date.parse
Create a date from a string.
-
Syntax
Date Date.parse(String s , [ Date rd ])
This function will create a date from an input string. The function is modelled over the PHP strtotime function and the uses the GNU Date Input Formats syntax.
The input string can be either absolute or relative. Accepted absolute formats are
Dates:
yyyy-mm-dd
yy-mm-dd
mm/dd/yyyy
Time
hh:mm
hh:mm:ss
hh:mm:ss.xxx (xxx are milliseconds)
You can also append am/pm to the time. Values less than 10 does not have to be prefixed with 0 but they can.
Accepted relative formats are
d|w i [ago], where
d is an integer optionally prepended with +/-
i is an interval. One of: year, month, week, day, hour, minute, second
w is a relative word. One of: last, this, next, first, third, forth...twelfth (note that 'second' is not available)
A relative format can also be a single word. One of: now, today, yesterday, tomorrow or fortnight (14 days)
There are some differences from the PHP implementation.
1. Timezones are not supported. As you can't change the timezone on the client it makes no sense.
2. Absolute and relative formats can not be mixed. -
Parameters
String s- The date input string.
Date rd(Optional)- A reference date. If not provided all calculations are relative to the current time.
- Return value The new date.
-
Examples
- To create a date using US format for 11th of feb. 1997
var d = Date.parse('2/11/97');- the same date could also be created using
var d = Date.parse('02/11/1997');- To use the current date and set the time to 11.23pm
var d = Date.parse('11:23pm');- or similar with seconds and milliseconds
var d = Date.parse('23:23:02.129');- To set the date and the time now using ISO date format
var d = Date.parse('1997-02-11 23:23:02.129');- Finally you can set the date using named months
var d = Date.parse('11 feb 1997 23:23:02.129');- Using a relative format you can advance the year of a date with
var d = Date.parse('next year');- or 24 years using a number (plural s is ignored)
var d = Date.parse('24 years');- adding the keyword ago will negate any prefixed numbers
var d = Date.parse('24 years ago'); // is equal to var d = Date.parse('-24 years');- You can also advance 2 years, 4 months and 3 minutes by
var d = Date.parse('2 years fourth month 3 minutes');
-
Download
Source
Unless otherwise noted all code in the JSLab Standard Library is licensed as GPLv3. See http://www.gnu.org/licenses/gpl.html for the entire license.
This function has dependencies and will not work stand-alone. Use the download button above instead of copy/paste.
