In this TypeScript tutorial, we will discuss the TypeScript Date. We will discuss how to create a 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 the typescript hello world program for beginners.
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, millisecond, etc in TypeScript.
TypeScript provides a 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 the following TypeScript Tutorials:
- TypeScript Enum (With Examples)
- TypeScript Dictionary (With Examples)
- TypeScript Map (Detailed Tutorial with Examples)
- TypeScript Set and Weakset (with Examples)
- Typescript hello world program for beginners
I Hope, this typescript tutorial helps to learn typescript date.
I am Bijay a Microsoft MVP (8 times –Â My MVP Profile) in SharePoint and have more than 15 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com