Home > Web Front-end > JS Tutorial > body text

How to convert timestamp to date format in javascript

青灯夜游
Release: 2021-06-18 15:21:58
Original
3935 people have browsed it

Method: 1. Use getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds() to convert the timestamp into year, month, day, hour, minute and second value; 2. Use " ” operator can be used to concatenate the converted year, month, day, hour, minute and second values.

How to convert timestamp to date format in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

We often need to convert timestamps into date format during development, but JavaScript’s own Date method is not as powerful as PHP date. Therefore, we need to write a method ourselves.

First of all, we need to understand the methods of the Date object that comes with JavaScript:

getDate: Get a certain day (1-31) in a

getFullYear: Get the complete year, for example: 2019

getMonth: Get the month (0-11) (ps: the base starts from 0)

getHours: Get the hour (0-23)

getMinutes: Get minutes (0-59)

getSeconds: Get seconds (0-59)

Through the above method, we can write a method for converting timestamps , please note that the timestamp must be accurate to milliseconds, because the timestamp unit returned by many backends is seconds. Let us look at the specific writing method:

function add0(m){return m<10?&#39;0&#39;+m:m }
function format(shijianchuo)
{
//shijianchuo是整数,否则要parseInt转换
var time = new Date(shijianchuo);
var y = time.getFullYear();
var m = time.getMonth()+1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y+&#39;-&#39;+add0(m)+&#39;-&#39;+add0(d)+&#39; &#39;+add0(h)+&#39;:&#39;+add0(mm)+&#39;:&#39;+add0(s);
}
Copy after login

Call:

console.log(format(1623999943284));
Copy after login

Output:

How to convert timestamp to date format in javascript

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to convert timestamp to date format 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