{

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


Unix timestamp is a long number, 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 Output Date format is MM/DD/YYYY and 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 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

toLocaleTimeString() method takes local and convert 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 doing manually getting Date and time For retrieving Date object, used getFullYear(),getMonth(), getDate() methods from 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 below 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.