距离明天还有多少秒?
重要性: 5
创建一个名为 getSecondsToTomorrow()
的函数,该函数返回距离明天还有多少秒。
例如,如果现在是 23:00
,那么
getSecondsToTomorrow
(
)
==
3600
注意:该函数应该在任何一天都起作用,不要硬编码“今天”。
要获取距离明天还有多少毫秒,我们可以从“明天 00:00:00”减去当前日期。
首先,我们生成“明天”,然后进行操作
function
getSecondsToTomorrow
(
)
{
let
now =
new
Date
(
)
;
// tomorrow date
let
tomorrow =
new
Date
(
now.
getFullYear
(
)
,
now.
getMonth
(
)
,
now.
getDate
(
)
+
1
)
;
let
diff =
tomorrow -
now;
// difference in ms
return
Math.
round
(
diff /
1000
)
;
// convert to seconds
}
另一种解决方案
function
getSecondsToTomorrow
(
)
{
let
now =
new
Date
(
)
;
let
hour =
now.
getHours
(
)
;
let
minutes =
now.
getMinutes
(
)
;
let
seconds =
now.
getSeconds
(
)
;
let
totalSecondsToday =
(
hour *
60
+
minutes)
*
60
+
seconds;
let
totalSecondsInADay =
86400
;
return
totalSecondsInADay -
totalSecondsToday;
}
请注意,许多国家/地区有夏令时 (DST),因此可能会有 23 或 25 小时的日子。我们可能需要分别处理这些日子。