{

Different ways to Convert Unix Timestamp into date and time in javascript


Javascript Convert Unix Timestamp into date and time

Unix timestamp is a long number, the number of milliseconds since 1970-01-01 UTC

console.log(Date.now()); //1641894862442

It is a long number also called UNIX timestamp, How do you convert this number to date and time format?

Input Unix timestamp is a long number and an example is 1641895275360 The output Date format is MM/DD/YYYY and the time format is HH:MM: SS.

How to convert Unix timestamp to date and time

There are multiple ways we can convert Unix timestamps.

  • use the toLocaleDateString method to convert timestamp to Date

First, create a Date object with a Unix timestamp, and call toLocaleDateString with Local information.

timestamp=1641895275360;
var todayDate = new Date(timestamp).toLocaleDateString("en-US")
console.log(todayDate)

Output:

1/11/2022
  • use the toLocaleTimeString method to convert timestamp to time

The toLocaleTimeString() method takes local and converts to time format.

timestamp=1641895275360;
var todayTime = new Date(timestamp).toLocaleTimeString("en-US")
console.log(todayTime)

Output:

10:01:15 AM
  • momentJS to convert Current timestamp to Date and time

momentJS is a javascript library that provides utility functions to manipulate date and time-related data.

var timestamp = moment.unix(1341895271360);
console.log( timestamp.format("hh:mm:ss") );

Output:

"11:59:20"
const date = moment(1341895271360).format('L');
console.log(date); // 4/17/2020

Output:

"07/10/2012"
  • use Inbuilt Date functions

This is a way of manually getting the Date and time For retrieving the Date object, used the getFullYear(),getMonth(), and getDate() methods from the Date object. getHours(),getMinutes(), getSeconds() method uses to return time

Here is an example.

function getDate(timestamp) {
  var date = new Date(timestamp);
  var year = date.getFullYear();
  var month = ("0" + (date.getMonth() + 1)).substr(-2);
  var day = ("0" + date.getDate()).substr(-2);


  return year + "-" + month + "-" + day ;
}
function getTime(timestamp) {
  var date = new Date(timestamp);

  var hour = ("0" + date.getHours()).substr(-2);
  var minutes = ("0" + date.getMinutes()).substr(-2);
  var seconds = ("0" + date.getSeconds()).substr(-2);

  return hour + ":" + minutes + ":" + seconds;
}
console.log( getDate(1641895271360));
console.log( getTime(1641895271360));

Output:

"2022-01-11"
"15:31:11"

Conclusion

Learned multiple ways to convert timestamp or epoch time to Date and time

  • toLocaleDateString and toLocaleTimeString
  • momentJS
  • Inbuilt Date functions
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.