var d = new Date();
var d = new Date(milliseconds); // milliseconds 为毫秒
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Date 对象常用的方法有:
date.
getFullYear
(
)
;
// 获取完整的年份(4位,1970)
date.
getMonth
(
)
;
// 获取月份(0-11,0代表1月,用的时候记得加上1)
date.
getDate
(
)
;
// 获取日(1-31)
date.
getTime
(
)
;
// 获取时间(从1970年1月1日开始的毫秒数)
date.
getHours
(
)
;
// 获取小时数(0-23)
date.
getMinutes
(
)
;
// 获取分钟数(0-59)
date.
getSeconds
(
)
;
// 获取秒数(0-59)
以下实例我们将时间戳转换 1655185405 秒转换为
yyyy-MM-dd hh:mm:ss
格式:
var
date
=
new
Date
(
1655185405
*
1000
)
;
// 参数需要毫秒数,所以这里将秒数乘于 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
(
)
;
document.
write
(
Y
+
M
+
D
+
h
+
m
+
s
)
;
尝试一下 »
我们也可以将日期转换为时间戳:
var
strtime
=
'2022-04-23 12:25:19'
;
var
date
=
new
Date
(
strtime
)
;
// 通过以下三种方式获时间戳
time1
=
date.
getTime
(
)
;
time2
=
date.
valueOf
(
)
;
time3
=
Date
.
parse
(
date
)
;
尝试一下 »
使用 Date() 获取系统当前时间,使用 getFullYear()、getMonth()、getDate() 、getHours()、getMinutes()、getSeconds() 等方法生成特定格式的时间
var
today
=
new
Date
(
)
;
var
DD
=
String
(
today.
getDate
(
)
)
.
padStart
(
2
,
'0'
)
;
// 获取日
var
MM
=
String
(
today.
getMonth
(
)
+
1
)
.
padStart
(
2
,
'0'
)
;
//获取月份,1 月为 0
var
yyyy
=
today.
getFullYear
(
)
;
// 获取年
// 时间
hh
=
String
(
today.
getHours
(
)
)
.
padStart
(
2
,
'0'
)
;
//获取当前小时数(0-23)
mm
=
String
(
today.
getMinutes
(
)
)
.
padStart
(
2
,
'0'
)
;
//获取当前分钟数(0-59)
ss
=
String
(
today.
getSeconds
(
)
)
.
padStart
(
2
,
'0'
)
;
//获取当前秒数(0-59)
today
=
yyyy
+
'-'
+
MM
+
'-'
+
DD
+
' '
+
hh
+
':'
+
mm
+
':'
+
ss
;
document.
write
(
today
)
;
尝试一下 »