Remember that TypeScript uses UTC as the primary time standard, allowing it to work with all local time zones if necessary.
Create A Date Object
You can use Date() as either a function or a constructor (with the new keyword).
As a constructor, it creates and returns a Date object representing a date and time that you require. When invoked as a function, the returned value is a string that represents the current date and time. All the arguments you provide will be ignored.
Remember those critical differences or you might end up with type-related errors in TypeScript.
There are multiple ways to use the Date() constructor. Here are some common variants of its syntax:
new Date() new Date(value) new Date(dateObject) new Date(dateString) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)
When you call the constructor without any argument, it will return a Date object representing the date and time at the time it is called.
let currentDate: Date; currentDate = new Date(); console.log(currentDate);
The first statement tells TypeScript currentDate is an instance of the interface Date. Then we assign the object returned by the Date() constructor to it.
currentDate is now a Date object that represents the moment in time when Date() is invoked. The console.log() method can print its string representation to the console.
You can provide the Date() constructor with an integer value to create an object representing a number of milliseconds from the ECMAScript epoch. Remember that this argument doesn’t take leap seconds into account.
let date1: Date = new Date(1000000000); console.log(date1);
In this example, the date1 object now points to a point that is 1000000000 milliseconds from the epoch, or around midday on January 12, 1970.
The range of this integer value should be within 8,640,000,000,000,000 and -8,640,000,000,000,000. Otherwise, the constructor will return a Date object whose string representation is “Invalid Date”.
Another argument you can provide the Date() constructor is a string that represents a date in the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ).
The constructor will use the Date.parse() method under the hood to parse your input and create a Date object accordingly. It treats date-only strings (such as “2022-11-01” as UTC, and date-time strings (like “2022-11-01T12:00” as local.
let date1: Date = new Date("2022-11-01"); console.log(date1);
If you already have a Date object, you can parse it to the Date() constructor too. A copy of the existing object will be created.
One of the most popular uses of the Date() constructor invokes individual component values of date and time. You can set the year, month, day, hours, minute, second, and millisecond for the Date object, all evaluated against your system’s local time zone.
Date() doesn’t require you to provide a value for every component. Any missing values will be filled automatically by the system, using the lowest possible values. In the simplest form, all you need is the year and month components.
let date1: Date = new Date(2022, 10); console.log(date1); console.log(date1.toLocaleString());
2022-10-31T17:00:00.000Z 11/1/2022, 12:00:00 AM
This example gives Date() only two components and will treat them as the year and month, respectively. Other fields will be filled by Date(), with 1 for day and 0 for other components).
However, if you print this Date object with console.log(), the output doesn’t look like what we have just described.
The reason is that this method produces the string representation in UTC, while the Date() constructor evaluates the date and time components in local time. You will need to use the toLocaleString() method, which returns the representation of the date and time in local time.
When you use Date() as a function, the returned value is a string. It can only produce the representation for the current date and time.
let date2: string; date2 = Date(); console.log(date2);
Sat Oct 08 2022 16:43:54 GMT+0700 (Indochina Time)
There is no object created, and you should use the string type to get the returned value of the Date() function.
If you want to get a specific component from a Date object, use these simple methods: getDate(), getDay(), getFullYear(), getMonth(), getHours(), get Minutes(), getSeconds(), getMilliseconds(), and so on.
Besides some exceptions, their purposes are quite self-explanatory:
let currentDate: Date = new Date(); console.log( currentDate.getFullYear(), currentDate.getMonth(), currentDate.getMonth(), currentDate.getDate(), currentDate.getDay(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getMinutes(), currentDate.getSeconds() );
2022 9 9 8 6 16 54 54 18
Remember that getDay() returns the day of the week, while getDate() returns the day of the month of a specific date.
Additionally, all those methods return values according to local time. Use their UTC versions (such as getUTCDate()) to get results in that time standard.
You can alter any component of an existing Date object with setFullYear(), setMonth(), setDate(), setHours(), setMinutes(), setSeconds(), setMilliseconds(), as well as the UTC versions.
let currentDate: Date = new Date(); console.log("Old date and time:", currentDate.toLocaleString()); currentDate.setFullYear(2020); currentDate.setMonth(3); currentDate.setDate(8); console.log("New date and time:", currentDate.toLocaleString());
Old date and time: 10/8/2022, 5:01:49 PM New date and time: 4/8/2020, 5:01:49 PM
To get the string representations of Date objects, use methods such as toDateString(), toTimeString(), toString(), etc.
Each of them typically has two other versions. For example, the toString() method interprets the Date object in the local timezone, toUTCString() in the UTC timezone, and toLocaleString() uses its language-sensitive representation.
let currentDate: Date = new Date(); console.log(currentDate.toString()); console.log(currentDate.toUTCString()); console.log(currentDate.toLocaleString());
Sat Oct 08 2022 17:07:02 GMT+0700 (Indochina Time) Sat, 08 Oct 2022 10:07:02 GMT 10/8/2022, 5:07:02 PM
Tutorials about TypeScript Dates
- How to format date/time in typescript
- How to type a date object in typescript
- Get the current date and time in TypeScript
- How to add Days to a Date in TypeScript
- Calculate the time between 2 Dates in TypeScript
- Get the difference between 2 Dates in Days using TypeScript
- How to compare Dates in TypeScript
My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.
Name of the university: HUST