Convert Unix Timestamp to Date in JavaScript
To convert a Unix timestamp into a formatted date in JavaScript, create a new Date()
object from the timestamp then format it using one of the various JavaScript Date()
methods available.
To demonstrate this, let's go through some common date formats that you may need to convert a Unix timestamp to.
Get the Full Date
To get the full date and time from a timestamp pass the timestamp as the first argument of Date()
and store the result (which will be a date object) in a variable like this:
var timestamp = 1622756602457;
var date = new Date(timestamp);
console.log(date);
Thu Jun 03 2021 22:43:22 GMT+0100 (British Summer Time)
Get the Day of the Month
To return only the day of the month, use the .getDate()
method like this:
var timestamp = 1622756602457;
var date = new Date(timestamp);
var day = date.getDate();
console.log(day);
3
Get The Month
To return only the month as a number, use the getMonth()
method like this:
var timestamp = 1622756602457;
var date = new Date(timestamp);
var month = date.getMonth();
console.log(month);
5
Get the Year
To get a four-digit year from a timestamp, use the getFullYear()
method like this:
var timestamp = 1622756602457;
var date = new Date(timestamp);
var year = date.getFullYear();
console.log(year);
2021
Get Hour Minutes or Seconds
Here are the methods to use if you need hours, minutes or seconds in a number format:
var timestamp = 1622756602457;
var date = new Date(timestamp);
var hour = date.getHours();
var mins = date.getMinutes();
var secs = date.getSeconds();
console.log(hour);
console.log(mins);
console.log(secs);
22
43
22
Custom Formatting a Date From a Unix Timestamp
Now we know some of the different methods for getting parts of a date from a JavaScript Date()
object we can combine them together to create custom date formats like this:
var timestamp = 1622756602457;
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDay();
var hour = date.getHours();
var mins = date.getMinutes();
var secs = date.getSeconds();
console.log(day +'/'+ month +'/'+ year +' '+ hour +':'+ mins +':'+ secs);
4/5/2021 22:43:22