Tutorial about Date and time in Javascript

Introduction

Date and time are used daily, and are an important part os using Javascript. To work with time and date Javascript use special object Date[1]. It stores date, time and gives methods to operate with them. This guide will teach you how to work with it, different interesting options and will help you to understand how to work with date and time in Javascript. There are several tricky and interesting use cases, which may make your life and work much easier:

Prerequisites:

1) Browser with Javascript support. For example you can just open CTRL+SHIFT+J in Chrome browser, switch to Console in the newly opened windows, and execute commands there.

Creation of new object

To create a new object of type Date use the following synthaxis: new Date() It creates a Date object with current time and date:

var now = new Date();
alert( now );

You can also create a new object date, that equals to the number of milliseconds that have passed from 1 January of 1970 GMT+0:

new Date(milliseconds)

Example, 24 hours after 1 of January 1970 GMT+0

var 24h1970 = new Date(3600 * 24 * 1000);
alert( 24h1970 );

If string is the only argument, Date.parse is used to read date from it, using

new Date(datestring)

For example:

new Date(year, month, date, hours, minutes, seconds, ms)

Date can be created, using components from local timezone. Only first 2 arguments are necessary, missing parameters, starting with hours, are considered to be zero, and starting with date - 1 Please remember 1) year must consist of 4 digits 2) months count starts with zero

new Date(2011, 0, 1, 0, 0, 0, 0); - 1 of January 2011, 00:00:00
new Date(2011, 0, 1); - same, but hours and seconds are 0 by default

Getting Date and time

Get exact date with milliseconds

var date = new Date(2011, 0, 1, 2, 3, 4, 567);
alert( date ); // 1.01.2011, 02:03:04.567

Getting date components:

getFullYear() - 4 digit year
getMonth() - get month, 0-11
getDate() - get month date, 1-31
getHours(), getMinutes(), getSeconds(), getMilliseconds() - get hours, minutes, seconds and milliseconds

IMPORTANT: Please always use getFullYear(). Some browsers support getYear(), but it is non standard, and return different output on different browsers. All of the above methods return results for local timezone.

There are also 2 specific non UTC symbols: Get the number of milliseconds, passed from 1 of January 1970, GMT+0, so basically the same as in contsructor new Date(milliseconds):

getTime()

Get difference between local time and UTC time, in minutes

getTimezoneOffset()

for example: alert( new Date().getTimezoneOffset() );

Setting time components:

setFullYear(year [, month, date])
setMonth(month [, date])
setDate(date)
setHours(hour [, min, sec, ms])
setMinutes(min [, sec, ms])
setSeconds(sec [, ms])
setMilliseconds(ms)
setTime(milliseconds)

They also have UTC analogs:

setUTCFullYear(year [, month, date])
setUTCMonth(month [, date])
setUTCDate(date)
setUTCHours(hour [, min, sec, ms])
setUTCMinutes(min [, sec, ms])
setUTCSeconds(sec [, ms])
setUTCMilliseconds(ms)
setUTCTime(milliseconds)

Some methods allow setting up multiple components simultaneously, in particular, setHours. If some component is not set, it does not change.

var thisday = new Date;
thisday.setHours(0);
alert( thisday ); // today, but hours are changed to 0
thisday.setHours(0, 0, 0, 0);
alert( thisday ); // today, but time is 00:00:00

Date autocorrection:

Autocorrection is a very useful property of Date objects. It means that you can set incorrect values for some components, and object will autocorrect itself for example:

var date = new Date(2014, 1, 32); // 32 of Februay 2014
alert(d) \\ it will be 4 of March 2014

Wrong data components are automatically spread during the other components: For example you want to go 2 days in advance from 31 of January 2010.

var td = new Date(2010, 0, 31);
td.setDate(td.getDate() + 2);
alert( td ); // 2 of February, 2010

We also can use it to get a date, that is far from current date on a set amount. For example, current date + 60 seconds

var td = new Date();
td.setSeconds(td.getSeconds() + 60);
alert( d )

Zero and negative values are also supported:

var td = new Date;
td.setDate(1); // 1 day of month
alert( td );
td.setDate(0); // there is no 0 day, last day of previous month will be used
alert( td );

var td = new Date;
td.setDate(-1); // the day before the last day of previous month
alert( d );

Formatting and date output:

All browsers, except for IE10, support new standard ECMA402[2], which adds new method to format date. It is done with date.toLocaleString(locale, options), which adds a lot of options

var date = new Date(2013, 10, 29, 11, 29, 0);

var options = {
  era: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long',
  timezone: 'UTC',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric'
};

alert( date.toLocaleString("en", options) ); 
alert( date.toLocaleString("de-DE", options) ); 

It will return date in english and in german.

No localisation methods of output: toString(), toDateString(), toTimeString() The return a standard string output, browser dependant. The only requirement is being human readable. toString() returns the whole date toDateString() - only date toTimeString() - only time

var td = new Date();
alert( td.toString() );

toUTCString() - same as toString(), but in UTC toISOString() - date in ISO format, not supported by IE8

var td = new Date();
alert( td.toISOString() );

Conclusion: Now you now how to operate with date and time in Javascript. This guide does not cover all aspects, but most used and interesting of them. It is enough to start working with Date() object and use it in your projects. If you want more in depth knowledge, feel free to read the developer mozilla network guide.[3]

[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
[2]: http://www.ecma-international.org/ecma-402/1.0/
[3]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date