Different ways to Convert Unix Timestamp into date and time in javascript
- Admin
- Mar 10, 2024
- Javascript
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, called UNIX timestamp, and an example is 1641895275360
How do you convert this number to date and time format in JavaScript?
The output Date format is MM/DD/YYYY
and the time format is HH:MM:SS
.
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 in milliseconds, and call toLocaleDateString
by passing local(en-US), converted to default date format(MM/DD/YYYY).
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(HH:MM:SS).
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. format()
method takes string format, converts it to date and time
var timestamp = moment.unix(1341895271360);
console.log(timestamp.format("MM-DD-YYYY hh:mm:ss"));
Output:
"11:59:20"
Another example is, format method takes āLā as the format
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 related information, call the getFullYear()
,getMonth()
, and getDate()
methods from the Date object. getHours()
,getMinutes()
, getSeconds()
method uses to get the 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