Home > Web Front-end > JS Tutorial > How to convert timestamp to time in javascript

How to convert timestamp to time in javascript

coldplay.xixi
Release: 2023-01-04 09:35:50
Original
7130 people have browsed it

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.

How to convert timestamp to time in javascript

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);
Copy after login

//Directly use new Date (timestamp) format to convert to obtain the current time

console.log(timestamp4);
Copy after login
console.log(timestamp4.toLocaleDateString().replace(/\//g, "-") + " " + timestamp4.toTimeString().substr(0, 8));
Copy after login

//Use splicing regularity and other methods to convert it into yyyy-MM-dd hh:mm:ss format

The effect is as follows:

How to convert timestamp to time in javascript

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);
        }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template