TypeScript – Date Object


TypeScript – Date Object


”;


In TypeScript, the ”Date” object is a built-in object that allows developers to create and manage dates and times. It is directly inherited from JavaScript, so it contains the same methods as the Date object in JavaScript. However, you need to ensure that typing of the Date object and return value from the Date methods in TypeScript.

Syntax

You can follow the syntax below to use the Date object in TypeScript.

let date: Date = new Date(); // Date Constructor
// OR
date = new Date(milliseconds); // Passes milliseconds
// OR
date = new Date(date_String); // Passes date string
// OR
date = new Date(year, month, day, hour, minute, second, milli_second); 

In the above syntax, we have explained 4 different ways to use the Date() constructor which takes different parameters.

Parameters

  • milliseconds: It is the total number of milliseconds since 1st January, 1971.

  • date_String: It is a date string containing year, month, day, etc.

  • year, month, day, hour, minute, second, milli_second: The Date() constructor creates a new date based on these parameters.

Return Value

The Date constructor returns the Date string based on the parameters passed. If we don”t pass any parameters, it returns the date string with the current time.

Examples

Let”s understand more about the date object with the help of some example in TypeScript.

Example: Creating New Dates

In the code below, first, we have created using the Date() constructor and without passing any parameters. It returns the current date and time.

Next, we have passed the milliSeconds as a parameter, and it returns the date according to the total milliseconds.

Next, we have passed the date in the string format as a parameter of the Date() constructor, and it returns a new date according to the date string.

Next, we have passed year, month, day, etc. as a separate parameter of the Date() constructor, which creates a new date string using the parameters.

let date: Date = new Date(); // Date Constructor
console.log(date); // Output: Current Date and Time

date = new Date(10000000000); // Passes milliseconds
console.log(date); // Output: 1970-04-26T17:46:40.000Z

date = new Date(''2020-12-24T10:33:30''); // Passes date string
console.log(date); // Output: 2020-12-24T10:33:30.000Z

date = new Date(2020, 11, 24, 10, 33, 30, 0); // Passes year, month, day, hour, minute, second, millisecond
console.log(date); // Output: 2020-12-24T10:33:30.000Z

On compiling, it will generate the following JavaScript code.

let date = new Date(); // Date Constructor
console.log(date); // Output: Current Date and Time

date = new Date(10000000000); // Passes milliseconds
console.log(date); // Output: 1970-04-26T17:46:40.000Z

date = new Date(''2020-12-24T10:33:30''); // Passes date string
console.log(date); // Output: 2020-12-24T10:33:30.000Z

date = new Date(2020, 11, 24, 10, 33, 30, 0); // Passes year, month, day, hour, minute, second, millisecond
console.log(date); // Output: 2020-12-24T10:33:30.000Z

Output

The output of the above example code will show the current date and provided custom dates.

Example: Accessing Date and Time Components

You can use the getFullYear() method to get the year from the date string. Similarly, the getMonth() and getDate() methods are used to get the month and day from the date string, respectively.

let someDate = new Date();
console.log(`Year: ${someDate.getFullYear()}`);  // Outputs current year
console.log(`Month: ${someDate.getMonth()}`);    // Outputs current month (0-indexed)
console.log(`Day: ${someDate.getDate()}`);       // Outputs current day

On compiling, it will generate the same JavaScript code.

let someDate = new Date();
console.log(`Year: ${someDate.getFullYear()}`);  // Outputs current year
console.log(`Month: ${someDate.getMonth()}`);    // Outputs current month (0-indexed)
console.log(`Day: ${someDate.getDate()}`);       // Outputs current day

Output

The output of the above example code will show the year, month and day of the current date.

Example: Adding Days to the Current Date

We can use different methods to manipulate the date string. Here, we have used the setDate() method to increment the days by 7 in the date string.

The getDate() method returns the date and we add 7 to that. After that, the new day we pass it to the parameter of the setDate() method.

The setDate() method automatically manages the changing the changing month or year. For example, if the current date is 30 and you want to add 7 days to that, it returns the new date with the next month.

let date = new Date();
date.setDate(date.getDate() + 7);  // Adds 7 days to the current date
console.log(date);  // Outputs the date 7 days in the future

On compiling, it will generate the same JavaScript code.

let date = new Date();
date.setDate(date.getDate() + 7);  // Adds 7 days to the current date
console.log(date);  // Outputs the date 7 days in the future

Output

Its output will show the date seven days ahead of the current date.

Example: Formatting a Date

We can use the different options to format the date string. Here, we have used the DateTimeFormatOptions() method to format the date string.

It takes the ”en-US” as a first parameter, which is a country code, and the options object as a second parameter. The options object contains the format details for the weekday, year, month, and day.

let today = new Date();
let options: Intl.DateTimeFormatOptions = { weekday: ''long'', year: ''numeric'', month: ''long'', day: ''numeric'' };
let formattedDate = new Intl.DateTimeFormat(''en-US'', options).format(today);
console.log(formattedDate);  // E.g., ''Tuesday, April 27, 2024''

On compiling, it will generate the following JavaScript code.

let today = new Date();
let options = { weekday: ''long'', year: ''numeric'', month: ''long'', day: ''numeric'' };
let formattedDate = new Intl.DateTimeFormat(''en-US'', options).format(today);
console.log(formattedDate); // E.g., ''Tuesday, April 27, 2024''

Output

The output of the above example code will produce the today”s date formatted in US format.

Example: Handling Time Zones

Here, we are handling different time zones in the code below. First, we have created the date according to the UTC using the UTC() method of the Date object and passed it as a parameter of the Date() constructor.

Next, we used the toLocaleString() method to change the date string according to the timezone. The toLocaleString() method takes the country code as a first parameter, and the object with the timeZone property as a second parameter.

let utcDate = new Date(Date.UTC(2024, 0, 1, 0, 0, 0));
console.log(utcDate.toISOString());  // Outputs ''2024-01-01T00:00:00.000Z''
console.log(utcDate.toLocaleString(''en-US'', { timeZone: ''America/New_York'' }));  // Adjusts to Eastern Time

On compiling, it will generate the same JavaScript code.

let utcDate = new Date(Date.UTC(2024, 0, 1, 0, 0, 0));
console.log(utcDate.toISOString());  // Outputs ''2024-01-01T00:00:00.000Z''
console.log(utcDate.toLocaleString(''en-US'', { timeZone: ''America/New_York'' }));  // Adjusts to Eastern Time

Output

Its output is as follows –

2024-01-01T00:00:00.000Z
12/31/2023, 7:00:00 PM

The Date object in TypeScript, inherited from JavaScript, provides a comprehensive set of functionalities for managing dates and times. By utilizing the Date object effectively, developers can perform a wide range of date and time manipulations, essential for applications that depend on temporal data.

Advertisements

”;

Leave a Reply

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