ArticleZip > Use Moment Js To Convert Unix Epoch Time To Human Readable Time

Use Moment Js To Convert Unix Epoch Time To Human Readable Time

Epoch time, also known as Unix time, is a way to represent time as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC) on January 1, 1970. While this timestamp is convenient for computers to work with, it's not the most human-friendly format. This is where Moment.js comes in to save the day!

Moment.js is a popular JavaScript library for parsing, validating, manipulating, and formatting dates. It makes working with dates and times in JavaScript a breeze, and one of its handy features is the ability to convert Unix epoch time to a human-readable format effortlessly.

To begin using Moment.js for converting epoch time to human-readable time, you first need to include the library in your project. You can do this by either downloading the library and adding it to your project manually or by using a package manager like npm or yarn to install it.

Once you have Moment.js set up in your project, you can start converting Unix epoch time to human-readable time. The process involves creating a Moment.js object using the epoch time as input and then formatting that object to the desired date and time format.

Here's a simple example to illustrate how you can achieve this:

Javascript

// Include Moment.js in your project (if you haven't already)
const moment = require('moment');

// Unix epoch time in seconds
const epochTime = 1632123456;

// Create a Moment.js object using the epoch time
const humanReadableTime = moment.unix(epochTime);

// Format the human-readable time as per your requirements
const formattedTime = humanReadableTime.format('YYYY-MM-DD HH:mm:ss');

console.log(formattedTime); // Output: 2021-09-20 15:50:56

In this example, we first import Moment.js into our project. We then create a Moment.js object using the `moment.unix()` function, passing the Unix epoch time as the argument. Finally, we format the resulting Moment.js object using the `format()` function with the desired date and time format string.

By customizing the format string in the `format()` function, you can display the date and time in various formats such as 'YYYY-MM-DD HH:mm:ss' for year-month-day hours:minutes:seconds.

Moment.js provides a wide range of formatting options, allowing you to tailor the output to suit your specific needs. Whether you prefer a long date format or a short time format, Moment.js has got you covered.

So, the next time you need to convert Unix epoch time to human-readable time in your JavaScript project, remember that Moment.js is here to simplify the process and make your life easier. Happy coding!

×