convert a unix timestamp to a date in javascript

To convert a Unix timestamp to a date in JavaScript, we can use the Date() constructor and pass in the timestamp as an argument. The constructor takes the number of milliseconds since January 1, 1970, so we need to multiply the timestamp by 1000. We can then use various methods of the Date() object to get different parts of the date.

index.tsx
// Unix timestamp (in seconds)
const unixTimestamp = 1620296152;

// Convert to milliseconds and create a new date object
const date = new Date(unixTimestamp * 1000);

// Get various parts of the date
const year = date.getFullYear();
const month = date.getMonth() + 1; // Months are zero-indexed
const day = date.getDate();
const hours = date.getHours();
const minutes = "0" + date.getMinutes(); // Add leading zero
const seconds = "0" + date.getSeconds(); // Add leading zero

// Format the date
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes.substr(-2)}:${seconds.substr(-2)}`;

console.log(formattedDate); // Outputs: 2021-05-06 14:22:32
660 chars
19 lines

In the above code block, we first define a Unix timestamp (in seconds). We then multiply this by 1000 to convert it to milliseconds and pass it as an argument to the Date() constructor to create a new date object. We can then use various methods of the Date() object to get the different parts (year, month, day, etc.) of the date. Finally, we format the date as a string using template literals and output it to the console.

gistlibby LogSnag