Date constructors in JavaScript

Published by admin on

JavaScript Date constructors with examples

JavaScript Date constructors :

new Date() :

new Date() creates one new Date object. It uses the current time at the time of initialization. For example :

let date = new Date();

console.log(date);

If you execute it, it will print something like below :

2020-02-21T01:12:02.136Z

This time is in UTC. But Date class provides a couple of useful methods to read the date & time values in local an utc format.

 

new Date(value) :

With this constructor, you need to pass one integer value. This is the number of seconds elapsed since January 1, 1970, 00:00:00 UTC, ignoring leap seconds. This value is similar to UNIX timestamp.

For example :

let date = new Date(0);

console.log(date);

This will print the starting time :

1970-01-01T00:00:00.000Z

Similarly,

let date = new Date(1577874025000);

console.log(date);

This will print :

2020-01-01T10:20:25.000Z

 

new Date(dateString) :

This is another way to create one Date. It takes one date string. It should be RFC 2822 or ISO8601 compliant date string. For example,

let date = new Date("2020-01-01T10:20:25Z");

console.log(date);

It will print :

2020-01-01T10:20:25.000Z

 

new Date(y, m [, d [, h [, min [, s [, ms]]]]]) :

This constructor can take all date time parameters individually. It takes day, month, year, hour, minute, seconds and milliseconds. If day is missing, it assigns 1 by default and if any other parameter is missing, it assigns 0.

Following are the details of each field :

  1. Year(y) : The value of year starts from 0. 0 represents 1900 and 99 represents 1999. For other years, you need to put the full year value.
  2. Month(m) : Month is also starts from 0. 0 is for January and it ends with 11 as December.
    Note that only year and month are required params. Other values are optional.
  3. Day(d) : Days of the month. Starts with 1.
  4. Hours(h) : This value starts from 0. 0 is for mid-night.
  5. Minute(min) : Integer number to represent the minutes passed. It starts from 0.
  6. Seconds(s) : Integer number to represent the seconds passed for the current minute. 0 is its start value.
  7. MilliSeconds(ms) : Integer value to define number of milliseconds passed for the current second. Start value is 0.

Let’s consider the below example :

let date = new Date(2020,08,02,03,04,05,06);

console.log(date.toString());

It will print the time on local timezone.

Categories: javascript

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *