TypeScript Date (With Examples)

In this TypeScript tutorial, we will discuss the TypeScript Date. We will discuss how to create date object in TypeScript. We will also discuss how to add days to date in typescript, date format in typescript, typescript date now etc.

If you are new to TypeScript, read my previous article on step by step tutorial on TypeScript.

You can download latest version of typescript (TypeScript 3.4).

TypeScript Date

The Date object represents a date and time functionality in TypeScript. We used date object to get or set the year, month and day, hour, minute, second, and millisecond, etc in TypeScript.

TypeScript provides Date library to perform an operation on Dates. Calling new Date() creates today’s Date.

Creating Date Object in TypeScript

new Date(): To create a new date object,there are four ways.

Example:

let date: Date = new Date();  
console.log(date)
//output:
2019-05-27T11:53:32.118Z

new Date(milliseconds): It creates a new date object as zero time plus milliseconds.

Example:

let date: Date = new Date(1600000000000);  
console.log(date)

//output:
2020-09-13T12:26:40.000Z

new Date(datestring): It creates a new date object from a date string.

Example:

let date: Date = new Date("2019-05-27");
console.log(date)
//output: 
2019-05-27T00:00:00.000Z

new Date ( year, month, date[, hour, minute, second, millisecond ]): It creates a new date object with a specified date and time.

Example:

let date: Date = new Date(2019,0o4,27,18,0o1,30,15); 
console.log(date) 
//output:
2019-05-27T18:01:30.015Z

We can access date components using various get methods.

Example:

let date: Date = new Date();  
console.log("Day: "+date.getDay())
console.log("Date: "+date.getDate())
console.log("Month: "+date.getMonth())
console.log("Year: "+date.getFullYear())

//output: 
Day: 1
Date: 27
Month: 4
Year: 2019

We can set date components using various set methods.

Example:

let date: Date = new Date();  
date.setDate(27)
date.setMonth(0o5)
date.setFullYear(2019)

console.log("Date: "+date.getDate())
console.log("Month: "+date.getMonth())
console.log("Year: "+date.getFullYear())

//output:
Date: 27
Month: 5
Year: 2019

You may like following TypeScript Tutorials:

Hope, this typescript tutorial helps to learn typescript date.

>