Date
is the standard class for representing points in time. You can create a
date object with new
and it defaults to the current date and time:
console.log(new Date());
You can also create objects for specific points in time:
console.log(new Date(2009, 11, 9))
// 2009-12-08T11:00:00.000Z
Note how the above output looks "wrong". That's because js
uses a really dumb
convension where month numbers start at 0 (December is thus 11), yet day numbers
start at one.
unix
You can print the unix timestamp (in milliseconds) with .getTime()
and you can
also create a date from a timestamp by creating a Date()
with a the timestamp
as the first and only argument.
methods
getFullYear
getMonth
getDate
getHours
getMinutes
getSeconds
parsing
Typically, parsing dates is done with regex:
function getDate(string) {
// underscore skips the full match returned in the array by exec
let [_, month, day, year] =
/(\d{1,2})-(\d{1,2})-(\d{4})/.exec(string);
return new Date(year, month - 1, day);
}
console.log(getDate("1-30-2003"))
// 2003-01-29T11:00:00.000Z