TypeScript Dates: How To Create And Use TS Dates And Times

TypeScript Dates

TypeScript dates are well supported and don’t represent any big departure from JavaScript. Learn more about them below.

TypeScript Dates

TypeScript recognizes JavaScript’s Date interface out of the box to represent single moments in time. The most important value of Date objects is the number of milliseconds since the epoch (January 1, 1970).

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.

new Date()

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);

Output:

2022-10-08T09:08:30.465Z

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);

Output:

1970-01-12T13:46:40.000Z

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);

Output:

2022-11-01T00:00:00.000Z

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());

Output:

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.

Date()

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);

Output:

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.

Date Methods

TypeScript Date objects support similar methods to those of Date objects in JavaScript.

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()
);

Output:

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());

Output:

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());

Output:

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

Summary

It is easy to transition to TypeScript dates if you are already familiar with those objects in JavaScript. Even when this isn’t the case, you should still have a solid understanding of this interface with the explanation above.

Leave a Reply

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