How to create date from year month day in Typescript?

In this Typescript tutorial, I will explain how to create date from year month day in Typescript.

To create a date in TypeScript from year, month, and day, you can use the JavaScript Date constructor. For example, new Date(year, month – 1, day) creates a new Date object, remembering to subtract 1 from the month since JavaScript counts months from 0 (January) to 11 (December). This approach is simple and effective for most use cases involving date creation in TypeScript projects.

Typescript create date from year month day

Creating a date from specific year, month, and day values is a common requirement in web development. TypeScript, being a superset of JavaScript, offers several methods to accomplish this.

Now, let us see various methods to create a date from year, month, and day in Typescript.

Method 1: Using the Date Constructor

The simplest way to create a date in TypeScript from year, month, and day is by using the Date constructor.

Note: The month parameter in JavaScript’s Date object is zero-indexed, meaning January is 0, February is 1, and so on. Hence, we subtract 1 from the month value.

function createDate(year: number, month: number, day: number): Date {
    return new Date(year, month - 1, day);
}

const myDate = createDate(2024, 4, 12);
console.log(myDate.toDateString());

Here, you can see the output in the screenshot below after running the code using VS code.

typescript create date from year month day

Method 2: Using Date.UTC()

Another method to create a date in TypeScript is by using the Date.UTC() method. This method is useful when you want to create a date in the UTC (Coordinated Universal Time) time zone.

Here is a complete code:

function createDateUTC(year: number, month: number, day: number): Date {
    return new Date(Date.UTC(year, month - 1, day));
}

const myUTCDate = createDateUTC(2024, 4, 12);
console.log(myUTCDate.toUTCString());
create date from year month day in Typescript

Method 3: Using Date.parse()

The Date.parse() method is another way to create a date from year month day in Typescript. It parses a date string and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

Here is the complete code:

function createDateFromString(year: number, month: number, day: number): Date {
    return new Date(Date.parse(`${year}-${month}-${day}`));
}

const myParsedDate = createDateFromString(2024, 4, 12);
console.log(myParsedDate.toDateString());
How to create date from year month day in Typescript

Conclusion

In TypeScript, creating a date from year, month, and day can be done in several ways using the Date constructor, Date.UTC(), or Date.parse(). In this tutorial, I have explained 3 different methods how to create date from year month day in Typescript.

You may also like:

>