The following summarizes the conversion between timestamp and date format in js:
1. Convert the timestamp to date format:
1
2
3
4
5
6
7
8
9
10
11
12
|
function
timestampToTime(timestamp) {
var
date =
new
Date(timestamp * 1000);
//时间戳为10位需*1000,时间戳为13位的话不需乘1000
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();
return
Y+M+D+h+m+s;
}
timestampToTime(1403058804);
console.log(timestampToTime(1403058804));
//2014-06-18 10:33:24
|
Note: Remember to multiply by 1000 if it is a Unix timestamp. For example, the timestamp obtained by the PHP function time() should be multiplied by 1000.
2. Convert the date format to a timestamp:
1
2
3
4
5
6
7
8
|
var
date =
new
Date(
'2014-04-23 18:55:49:123'
);
// 有三种方式获取
var
time1 = date.getTime();
var
time2 = date.valueOf();
var
time3 = Date.parse(date);
console.log(time1);
//1398250549123
console.log(time2);
//1398250549123
console.log(time3);
//1398250549000
|
The difference between the above three acquisition methods:
First, second: will be accurate to milliseconds
The third type: it can only be accurate to seconds, and the milliseconds are replaced by 000
The difference between the above three output results can be observed
Note: The obtained timestamp is divided by 1000 to obtain the Unix timestamp, which can be obtained by passing the value to the background.
Reprint address: https://www.cnblogs.com/crf-Aaron/archive/2017/11/16/7844462.html