Home >Web Front-end >JS Tutorial >How to convert timestamp to time in javascript
Javascript method to convert timestamp to time: First, directly use [new Date (timestamp)] format to convert to obtain the current time; then use splicing regularity and other means to convert it into [yyyy-MM-dd hh:mm :ss] format.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
Javascript method to convert timestamp to time:
var timestamp4 = new Date(1472048779952);
//Directly use new Date (timestamp) format to convert to obtain the current time
console.log(timestamp4);
console.log(timestamp4.toLocaleDateString().replace(/\//g, "-") + " " + timestamp4.toTimeString().substr(0, 8));
//Use splicing regularity and other methods to convert it into yyyy-MM-dd hh:mm:ss format
The effect is as follows:
However, this conversion will have unsatisfactory results on some browsers, because the toLocaleDateString() method varies from browser to browser. For example, IE is August 24, 2016 22:26:19 and the format Sogou is Wednesday, August 24, 2016 22:39:42
can be spliced by obtaining the year, month and day of the time respectively, for example:
function getdate() { var now = new Date(), y = now.getFullYear(), m = now.getMonth() + 1, d = now.getDate(); return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8); }
Related free learning recommendations: javascript Video tutorial
The above is the detailed content of How to convert timestamp to time in javascript. For more information, please follow other related articles on the PHP Chinese website!