convert relative date to actual date in typescript

To convert relative date to actual date in TypeScript, we can use the Moment.js library. Moment.js is a popular date manipulation library that provides a simple and consistent API for creating, manipulating, and formatting dates.

To get started with Moment.js, we need to install the library in our project.

npm install moment
19 chars
2 lines

Once we have installed Moment.js, we can use it to convert a relative date to an actual date in TypeScript by passing the relative date string to the moment() function and calling the toISOString() method to get the actual date in ISO format.

Here's an example code:

index.ts
import * as moment from 'moment';

const relativeDate = '2 hours ago';
const actualDate = moment(relativeDate).toISOString();

console.log(actualDate); // output: "2021-05-23T12:30:49.000Z"
190 chars
7 lines

In this example, we passed the relative date string "2 hours ago" to the moment() function, which created a Moment object representing the actual date and time 2 hours ago from the current time. We then called the toISOString() method on this Moment object to get the actual date in ISO format. The output is "2021-05-23T12:30:49.000Z".

gistlibby LogSnag