Easy Tutorial
❮ Python Extends Init Javascript Search Auto Tip ❯

JavaScript Timestamp to Date Format Conversion

Category Programming Techniques

This article introduces how to convert a timestamp to a date format using JavaScript.

The main application is the JavaScript Date object.

The Date object is used to handle dates and times.

Creating a Date object: new Date()

The following four methods can also create a Date object:

var d = new Date();
var d = new Date(milliseconds);  // milliseconds is in milliseconds
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
date.getFullYear();  // Get the full year (4 digits, 1970)
date.getMonth();     // Get the month (0-11, 0 represents January, remember to add 1 when using)
date.getDate();      // Get the day (1-31)
date.getTime();      // Get the time (milliseconds since January 1, 1970)
date.getHours();     // Get the hour (0-23)
date.getMinutes();   // Get the minutes (0-59)
date.getSeconds();   // Get the seconds (0-59)

In the following example, we will convert the timestamp 1655185405 seconds to the yyyy-MM-dd hh:mm:ss format:

Example

var date = new Date(1655185405 * 1000);  // The parameter needs milliseconds, so multiply the seconds by 1000 here
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds(); 
document.write(Y+M+D+h+m+s);

We can also convert the date to a timestamp:

Example

var strtime = '2022-04-23 12:25:19';
var date = new Date(strtime);
 
// Get the timestamp in the following three ways
time1 = date.getTime();
time2 = date.valueOf();
time3 = Date.parse(date);

Use Date() to get the current system time, and use methods such as getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds() to generate a time in a specific format:

Example

var today = new Date();

// Date
var DD = String(today.getDate()).padStart(2, '0'); // Get the day
var MM = String(today.getMonth() + 1).padStart(2, '0'); // Get the month, January is 0
var yyyy = today.getFullYear(); // Get the year

// Time
hh = String(today.getHours()).padStart(2, '0'); // Get the current hour (0-23)
mm = String(today.getMinutes()).padStart(2, '0'); // Get the current minutes (0-59)
ss = String(today.getSeconds()).padStart(2, '0'); // Get the current seconds (0-59)
today = yyyy + '-' + MM + '-' + DD + ' ' + hh + ':' + mm + ':' + ss;
document.write(today);

**Click to Share Notes

Cancel

-

-

-

❮ Python Extends Init Javascript Search Auto Tip ❯