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

Active March 02, 2022    /    Viewed 66    /    Comments 0    /    Edit


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

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount