Moment.js using with Typescript
In this article, we will learn how to use the Moment.js library with Typescript language. Typescript is a strongly-typed programming language that wraps JavaScript and gives it optional static typing. It is free and open source and is maintained by Microsoft.
Using Moment.js with Typescript: To use Moment.js with Typescript, we can use the data types provided by the Moment library by using Moment.js utility methods. Before proceeding further, please make sure to install the moment.js library using the below command:
npm install moment
Example 1: The below code returns the current date as a Moment object.
Javascript
import * as moment from "moment" ; class DateClass { public getDate(): moment.Moment { return moment(); } } const d = new DateClass(); console.log(d.getDate()); |
Output:
Example 2: The below code returns the current month as a number.
Javascript
import * as moment from "moment" ; class DateClass { public getMonth(): Number { return moment().month(); } } const d = new DateClass(); console.log(d.getMonth()); |
Output: