时间戳与年月日转换以及获取当前时间

时间戳转为年月日

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
getYMDHMS (timestamp) {
let time = new Date(timestamp)
let year = time.getFullYear()
let month = time.getMonth() + 1
let date = time.getDate()
let hours = time.getHours()
let minute = time.getMinutes()
let second = time.getSeconds()

if (month < 10) { month = '0' + month }
if (date < 10) { date = '0' + date }
if (hours < 10) { hours = '0' + hours }
if (minute < 10) { minute = '0' + minute }
if (second < 10) { second = '0' + second }
return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
//只获取年月日
return year + '-' + month + '-' + date
}



getYMDHMS (timestamp) {
let time = new Date(timestamp)
let year = time.getFullYear()
const month = (time.getMonth() + 1).toString().padStart(2, '0')
const date = (time.getDate()).toString().padStart(2, '0')
const hours = (time.getHours()).toString().padStart(2, '0')
const minute = (time.getMinutes()).toString().padStart(2, '0')
const second = (time.getSeconds()).toString().padStart(2, '0')
return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
//只获取年月日
return year + '-' + month + '-' + date
}
调用方式getYMDHMS(毫秒级时间戳)



function timestampToTime(cjsj){
//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var date = new Date(cjsj * 1000);
var Y = date.getFullYear() + ' ';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth()+1) : date.getMonth() + 1) + ' ';
var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes())+ ':';
var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
return Y + M + D + h + m + s;
}
调用方式timestampToTime(时间戳)

年月日转换为时间戳

1
2
3
4
5
6
function getTimeFormat(timeS){
let time = (new Date(timeS).getTime()) / 1000; //除1000 是变成秒级的时间戳 不除就是毫秒级
return time;
}
getTimeFormat('2022-02-02 02:22:22');
//输出结果为:1643739742(秒级时间戳)

jquery获取当前时间(年/月/日 时:分:秒)

1
2
3
4
5
6
7
8
9
10
11
12
13
function getNowDateTime(){
var now = new Date();
var year = now.getFullYear();
var month = (now.getMonth() + 1) < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1;
var dates = now.getDate() < 10 ? '0' + now.getDate() : now.getDate();
var hours = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
var minutes = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes();
var seconds = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds();
return year + "/" + month + "/" + dates + " " + hours + ":" + minutes + ":" + seconds;
}
$(function(){
console.log(getNowDateTime());
})

时间戳与年月日转换以及获取当前时间
https://huangzunxue998.top/2023/04/21/时间戳与年月日转换/
Author
黄dada
Posted on
April 21, 2023
Licensed under