Languages
[Edit]
EN

JavaScript - create date object

0 points
Created by:
Joanne-Senior
500

In this article, we would like to show you how to create date object in JavaScript.

Quick solution:

new Date()             // gets current date
new Date(dateString)   // dateString - String in a proper format
new Date(milliseconds) // milliseconds - Unix time * 1000
new Date(year, month, day, hours, minutes, seconds, milliseconds)

 

1. Current date

In this example, we use Date() constructor without any arguments to create a Date object initialized with the current datetime. Then we display the current datetime in ISO format.

// ONLINE-RUNNER:browser;

const date = new Date();

console.log(date.toISOString()); 

2. Date from date string

In this example, we use Date() constructor with one argument to create the date object from a date string in a proper format. Then we display the date in ISO format.

// ONLINE-RUNNER:browser;

const dateString = '2021-09-07T15:55:00.000Z';    // String in a proper format
const date = new Date(dateString);

console.log(date.toISOString());

Output:

2021-09-07T15:55:00.000Z

3. Date from Unix time

In this example, we use Date() constructor with one argument to create the date object from unix time. To do so, we need to convert timestamp to milliseconds by multiplying it by 1000. Then we display the date in ISO format.

// ONLINE-RUNNER:browser;

const timestamp = 1630564245;     // unix timestamp in seconds
const date = new Date(timestamp * 1000);

console.log(date.toISOString());  // 2021-09-02T06:30:45.000Z

Output:

2021-09-02T06:30:45.000Z

4. Date from specified parameters

In this example, we use Date() constructor with many arguments to create the date object from specified data. Then we display the date in ISO format.

Syntax:

new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)

Practical example: 

// ONLINE-RUNNER:browser;

const year = 2021;
const monthIndex = 9; // 0-January, 1-February... 11-December
const day = 7;
const hours = 15;
const minutes = 0;
const seconds = 0;
const milliseconds = 0;

const date = new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)

console.log(date.toISOString());  // 2021-10-07T13:00:00.000Z

Output:

2021-10-07T13:00:00.000Z

Note:

The hour in ISO format may be different depending on the time zone you live in. My time is currently given in GMT+0200 (Central European Summer Time), that's why ISO format subtracts 2 hours (from 15 to 13).

References

Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join