How to create a date object in javascript for the current date or for a given year, month and day ?

Published: March 02, 2022

Updated: December 09, 2022

Tags: Javascript;

DMCA.com Protection Status

Examples of how to create a date object in javascript:

Create a date object in javascript for the current date

To create a date object in javascript there is the Date() constructor. A simple utilisation of date() is to get the current date:

var now = new Date();

console.log( now );

returns for example

Wed Mar 02 2022 13:46:30 GMT-0500 (Eastern Standard Time)

Create a date object in javascript using year, month and day

To create a date for a given year, month and day:

var year = 2008;
var month = 7; 
var day = 8;

var date = new Date(year,month,day);

console.log( date );

gives

Fri Aug 08 2008 00:00:00 GMT-0400 (Eastern Daylight Time)

Warning: JavaScript counts months from 0 to 11:

January 0
February 1
March 2
April 3
May 4
June 5
July 6
August 7
September 8
October 9
November 10 
December 11

Note (1): also work if year, month and day are strings:

var year = '2008';
var month = '7'; 
var day = '8';

console.log( typeof year );

gives

string

and

var date = new Date(year,month,day);

console.log( date );

also returns:

Fri Aug 08 2008 00:00:00 GMT-0400 (Eastern Daylight Time)

Note (2): same

var date = new Date( '2008/08/08' );

also returns:

Fri Aug 08 2008 00:00:00 GMT-0400 (Eastern Daylight Time)

Note (3): however

var date = new Date( '2008-08-08' );

console.log( date );

might returns (see Javascript Date string constructing wrong date)

Thu Aug 07 2008 20:00:00 GMT-0400 (Eastern Daylight Time)

since here the browser interprets the dashes that the time is in UTC and a negative offset from UTC will correspond to the previous day (7 instead of 8 here).

Retrieve year, month and day associated with a date object

To get date object year:

console.log( 1900 + date.getYear() );

gives

2008

To get date object month:

console.log( date.getMonth() );

gives

7

To get date object day:

console.log( date.getDate() );

gives

8

Date difference

Date objects cab be then use to caculaute for example the difference between two dates:

var date1 = new Date(2020,4,10);
var date2 = new Date(2020,4,22);
var date_diff = date2 - date1;

console.log( date_diff );

returns

1036800000

the difference between two dates in millisecondes.

To get the difference in days:

console.log( Math.floor( date_diff / (1000*60*60*24)) );

returns

12