Andrea Azzola

Technology, Personal Development and Financial Independence

Manage and format Dates with JavaScript

Posted on [Permalink]

JavaScript has a Date object wich you can use to handle dates. Supported constructors are:

new Date() // with current date and time
new Date(numeric) // by adding N milliseconds to the Unix epoch time (1970-01-01T00:00:00Z)
new Date(year, month, day, hour, minute, second, millisecond)
new Date(year, month, day) // the time part will equal "00:00.000"

There are some built-in methods that can be used to extract or set dateparts:

.getDate() // get the day part [1-31]
.getDay() // get the week day [0-6]
.getFullYear() // get the four digits year part
.getHours() // get the hour part
.getMinutes() // get the minutes part
.getSeconds() // get the seconds part
.getMilliseconds() // get the millisencond part

.setDate() // set the day part [1-31]
.setDay() // set the week day [0-6]
.setFullYear() // set the four digits year part
.setHours() // set the hour part
.setMinutes() // set the minutes part
.setSeconds() // set the seconds part
.setMilliseconds() // set the millisencond part

And their UTC variant:

.getDate() // get the UTC date day part [1-31] 
.getUTCDay() // get the UTC week day [0-6] 
.getUTCFullYear() // get the UTC four digits year part 
.getUTCHours() // get the UTC hour part 
.getUTCMinutes() // get the UTC minutes part 
.getUTCSeconds() // get the UTC seconds part 
.getUTCMilliseconds() // get the UTC millisecond part 

.setUTCDate() // set the UTC day part [1-31] 
.setUTCDay() // set the UTC week day [0-6] 
.setUTCFullYear() // set the UTC four digits year part 
.setUTCHours() // set the UTC hour part 
.setUTCMinutes() // set the UTC minutes part 
.setUTCSeconds() // set the UTC seconds part 
.setUTCMilliseconds() // set the UTC millisecond part

As per formatting, there are two simple options:

1) A combo of the aforementioned methods

var myDate = new Date();
alert(myDate.getFullYear() + '-' + myDate.getMonth() + '-' myDate.getDay());

2) A dedicated library like Moment.js

var myDate = moment(new Date(1970, 1, 1));
myDate.format('MMMM Do YYYY, h:mm:ss a'); // displays January 1st 1970, 1:00:00 pm
myDate.format('dddd'); // displays Thursday
myDate.format(); // displays 1970-01-01T00:00:00+00:00

Moment.js also supports validations, UTCtimespans and many more...

Categories: JavaScript