TypeScript - create date object
In this article, we would like to show you how to create date object in TypeScript.
Quick solution:
xxxxxxxxxx
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)
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.
xxxxxxxxxx
const date: Date = new Date();
console.log(date.toISOString());
Example output:
xxxxxxxxxx
2022-03-22T14:03:02.393Z
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.
xxxxxxxxxx
const dateString: string = '2021-09-07T15:55:00.000Z'; // String in a proper format
const date: Date = new Date(dateString);
console.log(date.toISOString());
Output:
xxxxxxxxxx
2021-09-07T15:55:00.000Z
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.
xxxxxxxxxx
const timestamp: number = 1630564245; // unix timestamp in seconds
const date: Date = new Date(timestamp * 1000);
console.log(date.toISOString());
Output:
xxxxxxxxxx
2021-09-02T06:30:45.000Z
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:
xxxxxxxxxx
new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)
Practical example:
xxxxxxxxxx
const year: number = 2021;
const monthIndex: number = 9; // 0-January, 1-February... 11-December
const day: number = 7;
const hours: number = 15;
const minutes: number = 0;
const seconds: number = 0;
const milliseconds: number = 0;
const date: Date = new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds);
console.log(date.toISOString());
Output:
xxxxxxxxxx
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
to13
).