Categories
JavaScript Answers

How to Convert a Unix Timestamp to a Calendar Date with Moment.js and JavaScript?

Spread the love

Sometimes, we want to convert a Unix timestamp to a calendar date with Moment.js and JavaScript.

In this article, we’ll look at how to convert a Unix timestamp to a calendar dare with moment.js and JavaScript.

Use the unix and format Methods

We can use the unix method to create a moment object from a timestamp.

Then we can use the format method to format the date into a calendar date.

For instance, we can write:

import moment from 'moment'  
const dt = +new Date(2021,1,1)  
const dateString = moment.unix(dt / 1000).format("MM/DD/YYYY");  
console.log(dateString)

We create the dt date object with the Date constructor.

Then we convert it to a timestamp in milliseconds with the unary + operator.

Next, we call moment.unix with a timestamp in seconds.

And then we call format to format the date into MM/DD/YYYY format.

And so dateString is ‘02/01/2021’ .

Use the moment Function and the format Method

We can just use the moment function without the unix method to create a moment object from a timestamp.

For instance, we can write:

import moment from 'moment'  
const dt = +new Date(2021,1,1)  
const dateString = moment(dt).format("MM/DD/YYYY");  
console.log(dateString)

The moment function takes a timestamp in milliseconds.

Therefore, we don’t have to divide dt by 1000 when we pass it in.

The rest of the code is the same and we get the same result as before.

Conclusion

We can convert a timestamp to a calendar date with format with the moment function or the unix method with the format method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *