Working with Date Types in TypeScript
Working with Date Types in TypeScript
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. As such, it supports a wide range of data types which includes date types like Date, Time, and Moment.js.
Let’s take a look at the basics of working with date types in TypeScript.
Getting and Setting Date Values
The most basic way to work with dates in TypeScript is to use the Date type. You can create a new Date object by passing in a string containing a valid date as a parameter.
let myDate = new Date("Jan 1 2019");
You can set and retrieve individual date values using the getFullYear(), getMonth(), and getDay() methods.
let year = myDate.getFullYear(); // returns 2019 let month = myDate.getMonth(); // returns 0 for January let day = myDate.getDay(); // returns 1 for Monday
Formatting Date Strings
Creating strings from date objects can be done with the toLocaleString() method. This method takes an optional parameter which is an array of options to format the date string.
let formattedDate = myDate.toLocaleString(['en-US']); // returns "1/1/2019"
You can also pass in an array of options to output a certain date format. For example, to output the date as "January 1, 2019":
let formattedDate = myDate.toLocaleString(['en-US'], {month: 'long', day: 'numeric', year: 'numeric'}); // returns "January 1, 2019"
Time/Duration between Dates
You can calculate the time or duration between two dates using the getTime() method. This method returns the number of milliseconds since January 1, 1970.
let startDate = new Date("Jan 1 2019"); let endDate = new Date("Dec 1 2019"); let duration = endDate.getTime() - startDate.getTime(); // returns 31536000000 (milliseconds)
Once you have the duration in milliseconds, you can easily convert it to days, hours, minutes, etc. For example, to convert to days you would divide by 1000 * 60 * 60 * 24.
Using Moment.js to Work with Date and Time
Moment.js is a popular JavaScript library that provides powerful functions for parsing, manipulating, and formatting date and time. It has an API that is very similar to the native Date type and makes it easy to work with dates in TypeScript.
To use Moment.js in your project, install it via npm:
$ npm install moment
Then you can import the library and begin using it in your TypeScript files.
import moment from 'moment'; let myDate = moment("Jan 1 2019"); let formattedDate = myDate.format('LL'); // returns "January 1, 2019"
For more information on using Moment.js, check out the official documentation.