Ever found yourself tangled up in the wild west of dates and times in TypeScript? Well, you’ve hit the jackpot with this article because we’re about to crack open the Date object in TypeScript and explore all its nooks and crannies.
The Date object in TypeScript is used to store, manipulate, and compare date and time values. To create a Date object in Typescript, you can either use the default constructor that stores the current date and time or pass arguments to the constructor for a custom date.
In this article, we’ll explore how to work with dates and times in TypeScript. We’ll cover the Date object, methods for manipulating, formatting, and displaying dates, and advanced techniques with libraries like Moment.js.
By the end, you’ll have a solid grasp of date handling in TypeScript to apply to your own projects.
Let’s get started!
Understanding TypeScript Date Objects
The Date object in TypeScript, and in JavaScript, is a built-in object for handling dates and times.
When you create a Date object, you get access to several Typescript Date object properties which are essentially the methods that you can call on the Date object. To make a new date object in Typescript, you can use the Date() constructor.
Let’s see how you can create a Date object:
Date() Constructor
The Date() constructor function is used to create and initialize a new Date object. You use it by invoking the new Date() syntax.
The constructor function accepts four different types of arguments:
- No arguments: Creates a Date object with the current date and time.
- One numeric argument: Parses the argument as the number of milliseconds since January 1, 1970 (also known as the Unix Epoch).
- Multiple arguments: Specifies the year, month, day, hours, minutes, seconds, and milliseconds.
- One string argument: Parses the argument as a date according to universal time.
For instance, look at the following code:
const date1 = new Date(); // Current date and time
console.log(date1);
const date2 = new Date(1623765902000); // Date from milliseconds since the Unix Epoch
console.log(date2);
const date3 = new Date(2023, 5, 14); // June 14, 2023
console.log(date3);
Let’s break down the use of Date() constructor in the example code above:
Here’s the output of the three date objects created in the code above:
TypeScript Date Methods
When you’re working with TypeScript, you’ll find a variety of handy methods that are part of the Date object due to the Date object’s prototype. These methods let you perform operations on dates, such as:
- Getting date properties
- Setting date properties
- Manipulating date properties
Let’s explore the many built-in methods available for Typescript Date object:
1. Year and Month
To access and change the year and month components of a specified date, you can use the following date methods:
- getFullYear(): This allows you to obtain the full year (e.g., 2023) of the specified date.
- getMonth(): Use this to get the month index (0-11, where 0 represents January) of the specified date.
- setFullYear(year, [month], [day]): Use this to set the year, and if needed, the month and day of the Date object.
- setMonth(month, [day]): This sets the month and optionally the day of the Date object.
The example below shows how these methods can be used:
const date = new Date();
const year = date.getFullYear(); // e.g., 2023
const month = date.getMonth(); // e.g., 7 (for July)
console.log(`Current Year: ${year}, Current Month: ${month}`);
date.setFullYear(2022);
date.setMonth(7);
const updatedYear = date.getFullYear();
const updatedMonth = date.getMonth();
console.log(`Updated Year: ${updatedYear}, Updated Month: ${updatedMonth}`);
Let’s see what’s going on in the above code:
Here is the output:
2. Day and Hours
Handling day and hours components is also fairly easy with the following methods:
- getDate(): Returns the date component (1-31) of the specified date.
- getDay(): Returns the day of the week (0-6, where 0 represents Sunday) of the specified date.
- getHours(): Returns the hours component (0-23) of the specified date.
- setDate(day): Sets the day of the month.
- setHours(hours, [minutes], [seconds], [ms]): Sets the hours (and optionally the minutes, seconds, and milliseconds) of the Date object.
Let’s see an example of how these can be used:
const date = new Date();
const day = date.getDate(); // e.g., 14
const weekday = date.getDay(); // e.g., 3 (for Wednesday)
const hours = date.getHours(); // e.g., 12 (for 12 PM)
console.log(`Current Day: ${day}, Current Weekday: ${weekday}, Current Hours: ${hours}`);
date.setDate(15);
date.setHours(14);
const updatedDay = date.getDate();
const updatedHours = date.getHours();
console.log(`Updated Day: ${updatedDay}, Updated Hours: ${updatedHours}`);
Here’s the output showing the current date stored in a new date instance before being updated using the setDate() and setHours() methods.
3. Minutes and Seconds
You can even retrieve and set minutes and seconds components in the Date object using the following methods:
- getMinutes(): Returns the minutes component (0-59) of the specified date object.
- getSeconds(): Returns the seconds component (0-59) of the specified date object.
- setMinutes(minutes, [seconds], [ms]): Sets the minutes (and optionally the seconds and milliseconds) of the Date object.
- setSeconds(seconds, [ms]): Sets the seconds (and optionally the milliseconds) of the Date object.
These methods can be used just like the ones we saw above:
const date = new Date();
const minutes = date.getMinutes(); // e.g., 30 (for 30 minutes)
const seconds = date.getSeconds(); // e.g., 45 (for 45 seconds)
console.log(`Current Minutes: ${minutes}, Current Seconds: ${seconds}`);
date.setMinutes(20);
date.setSeconds(15);
const updatedMinutes = date.getMinutes();
const updatedSeconds = date.getSeconds();
console.log(`Updated Minutes: ${updatedMinutes}, Updated Seconds: ${updatedSeconds}`);
Here’s the output:
4. Milliseconds
Finally, you can deal with the milliseconds component of a date function using the methods given below:
- getMilliseconds(): This returns the milliseconds (0-999) from the specified Date object.
- setMilliseconds(milliseconds): Use this to set the milliseconds of the Date object.
Now, let’s see an example of setting everything including the year, month, date, hours, minutes, seconds, and milliseconds according to local time zone.
let tsDate = new Date();
tsDate.setFullYear(2023);
tsDate.setMonth(5);
tsDate.setDate(14);
tsDate.setHours(10);
tsDate.setMinutes(30);
tsDate.setSeconds(0);
tsDate.setMilliseconds(0);
console.log(tsDate);
The following output shows the specified date:
Note that the above output is shown in the universal time.
5. UTC and Time Zone Methods
TypeScript also provides getter and setter methods for handling dates in UTC format. UTC stands for Coordinated Universal Time, and it’s used as the basis for time zones worldwide.
Some commonly used UTC getter methods are:
- getUTCFullYear(): Returns the year from the specified date according to universal time convention
- getUTCMonth(): Returns the month (0-11) from the specified date according to universal time convention
- getUTCDate(): Returns the day of the month (1-31) from the specified date according to universal time convention
- getUTCDay(): Returns the day of the week (0-6) from the specified date according to universal time convention
- getUTCHours(): Returns the hour (0-23) from the specified date according to universal time convention
- getUTCMinutes(): Returns the minute (0-59) from the specified date according to universal time convention
- getUTCSeconds(): Returns the seconds (0-59) from the specified date according to universal time convention
- getUTCMilliseconds(): Returns the milliseconds (0-999) from the specified date according to universal time convention
The corresponding setter methods are also available for updating date components in UTC format:
- setUTCFullYear(year): Sets the year in UTC format
- setUTCMonth(month): Sets the month (0-11) in UTC format
- setUTCDate(date): Sets the day of the month (1-31) in UTC format
- setUTCHours(hours): Sets the hour (0-23) in UTC format
- setUTCMinutes(minutes): Sets the minutes (0-59) in UTC format
- setUTCSeconds(seconds): Sets the seconds (0-59) in UTC format
- setUTCMilliseconds(milliseconds): Sets the milliseconds (0-999) in UTC format
let tsUTCDate = new Date();
tsUTCDate.setUTCFullYear(2023);
tsUTCDate.setUTCMonth(5);
tsUTCDate.setUTCDate(14);
tsUTCDate.setUTCHours(10);
tsUTCDate.setUTCMinutes(30);
tsUTCDate.setUTCSeconds(0);
tsUTCDate.setUTCMilliseconds(0);
console.log(tsUTCDate);
This gives the following output showing the specified date in UTC time:
Formatting Dates in TypeScript
When working with dates and times in TypeScript, you must know how to format them for proper presentation and processing as per your requirement.
In this section, we’ll explore different methods available in TypeScript for formatting dates and working with strings, locales, and time zones.
1. Date String Formats
A common requirement is to represent a specific date or time in a specific string format. Following are some of the commonly used methods to convert a Date to a string in Typescript:
- toString(): Converts the date and time from the specified date object to a human-readable string representation.
- toDateString(): Converts the date to a more human-readable format like “Wed Jun 14 2023”.
- toISOString(): Converts the date and time to the ISO 8601 format (e.g., “2023-06-14T00:00:00.000Z”).
- getTime(): Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
Let’s see these in action:
const date = new Date('2023-06-14');
console.log(date.toString());
console.log(date.toDateString());
console.log(date.toISOString());
console.log(date.getTime());
The above code gives the following output:
2. Locale and Time Zone Handling in Date Object
You can also handle different locales and time zones by using the following TypeScript Date object methods:
- toLocaleString(): Returns a string with a formatted date according to local time zone.
- toLocaleDateString(): Returns a string with a formatted specified date according to the current locale’s conventions, excluding the time part.
- toLocaleTimeString(): Returns a human-readable string with a formatted specified time according to the user’s current locale, excluding the date part.
- getTimezoneOffset(): Returns the time zone offset, in minutes, from the current locale to UTC.
These methods accept optional arguments to specify the locale, options for formatting the locale-specific date, and time, and the desired format.
Here’s an example:
const date = new Date('2023-07-23');
console.log(date.toLocaleString('en-US'));
console.log(date.toLocaleDateString('en-US'));
console.log(date.toLocaleTimeString('en-US'));
console.log(date.getTimezoneOffset());
The output of the above code is:
Advanced Date Manipulation in TypeScript
Once you’re comfortable with TypeScript’s built-in Date methods, you can further enhance your date handling capabilities using advanced techniques like date manipulation libraries and leveraging TypeScript’s static type system.
Let’s discuss this next.
1. Date Libraries and Moment.js
Using a date library can simplify the process of handling and manipulating dates compared to using the built-in Date object. A popular JavasScript date library you can use is Moment.js.
Moments.js provides support for date operations such as calculations, formatting, and parsing. It enables dates to be handled via a consistent API that accounts for issues like timezone management, leap years, and date formatting.
For example, if you are working with a date in the “dd-mm-yyyy” format, Moment.js simplifies this task with its robust methods:
import * as moment from 'moment';
const date = moment("14-06-2022", "DD-MM-YYYY");
console.log(date.format("YYYY-MM-DD")); // Output: 2022-06-14
The above example gives the following output:
2. Type Definitions and Union Types
TypeScript allows for the use of Type Definitions and Union Types when working with dates. Type Definitions specify the expected types that a given date library, such as Moment.js, should work with. This ensures proper type-checking and code robustness when using these third-party libraries.
For instance, with Moment.js, you can create a custom MomentDate type definition for better type checking:
interface MomentDate {
format: (format: string) => string;
}
const convertDate = (date: MomentDate): string => {
return date.format("YYYY-MM-DD");
};
Let’s analyze what we are doing in this code:
First, we create a function that accepts a union type as an input. This can be useful while working with different formats of dates, like “dd-mm-yyyy“, “yyyy-mm-dd“, or ISO 8601 format.
Next, we call the moment.format() method to convert the date into the specified format.
Here is the output:
The following is an example of using Union Types and Type Guards to handle various date formats:
import * as moment from 'moment';
type DateFormat = 'DD-MM-YYYY' | 'YYYY-MM-DD' | 'ISO 8601';
const parseDate = (date: string, format: DateFormat): string | null => {
let momentDate = moment(date);
if (!momentDate.isValid()) {
return null;
}
if (format === 'DD-MM-YYYY') {
return momentDate.format('DD-MM-YYYY');
} else if (format === 'YYYY-MM-DD') {
return momentDate.format('YYYY-MM-DD');
} else if (format === 'ISO 8601') {
return momentDate.toISOString();
} else {
return null;
}
};
// Test the function with various formats
console.log(parseDate('2023-07-23', 'DD-MM-YYYY'));
console.log(parseDate('2023-07-23', 'YYYY-MM-DD'));
console.log(parseDate('2023-07-23', 'ISO 8601'));
In the above example, the TypeScript function parseDate accepts a date as a string and a desired format.
It uses Moment.js to parse the input date and return a new string representing the exact date, in the desired format, or returns null if the date is invalid or the format isn’t recognized.
Here is the output:
Final Thoughts
You’ve now embarked on the journey of handling dates in TypeScript, an important aspect of developing robust applications. As you have discovered, TypeScript is equipped with various tools and constructs that make working with dates a smooth and efficient process.
Remember that the fundamental pillar of this process is the Date() constructor, which allows us to generate instances of date objects. These objects are then manipulated through various properties and methods to get or set different components of the date object.
We encourage you to use the knowledge you gained here and apply it to real-world projects, experimenting with the various methods and techniques discussed.
And, don’t forget to refer back to TypeScript’s documentation and online communities for further learning and support. Enjoy coding with TypeScript!
If you’d like to learn more about how to work with dates beyond TypeScript, check out the video below:
Frequently Asked Questions
How to format a date in TypeScript?
In TypeScript, you can format a date using the toLocaleDateString, toLocaleTimeString, or toLocaleString methods.
The following is an example:
const currentDate: Date = new Date();
console.log(currentDate.toLocaleDateString()); // Prints the date in the format "MM/DD/YYYY"
And here is the output of the above example:
How to use DateTime in TypeScript?
In TypeScript, there is no native DateTime type. Instead, you use the Date object for handling both date and time value parts.
For example, see the following code in which store the current date and time in new constant datetime:
const datetime: Date = new Date(); // Creates a Date object with the current date and time
console.log(datetime);
As shown in the output below, the new date object stores both the current date and time.
What is a common method to create a formatted date in TypeScript?
A common approach to creating a formatted date in TypeScript is by using the Intl.DateTimeFormat object:
const currentDate: Date = new Date();
// Create the first formatter
const formatter1 = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
const formattedDate1: string = formatter1.format(currentDate);
console.log(formattedDate1); // Prints the date in the format "June 14, 2023"
// Create the second formatter
const formatter2 = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: '2-digit' });
const formattedDate2: string = formatter2.format(currentDate);
console.log(formattedDate2); // Prints the date in the format "Jun 14, 2023"
In the example above, two Intl.DateTimeFormat objects, formatter1 and formatter2, are created.
The first one shows the full month name and numeric date and year, while the second one shows a shorter name for the month and forces the date to always show with two digits.
How to represent a date with an interface in TypeScript?
To create a new date with an interface in TypeScript, add properties with data type Date. For example, see the following code:
interface Event {
name: string;
date: Date;
}
const someEvent: Event = {
name: "Birthday party",
date: new Date("2023-06-14")
};
// Print the name and date of the event
console.log(`Event name: ${someEvent.name}, Event date: ${someEvent.date}`);
In this example, we’ve defined the Event interface with name and date properties. Then, we created the someEvent object, which is of type Event. The name is set to “Birthday party”, and the date is set to June 14, 2023.
Here’s the output: