3 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
我能想到的最簡(jiǎn)單的方法是將日期增加 12 小時(shí),然后截?cái)鄷r(shí)間部分。這具有四舍五入到最近日期的效果(中午之前的任何時(shí)間都會(huì)被截?cái)啵蟮娜魏螘r(shí)間都會(huì)被截?cái)嗟降诙?,然后時(shí)間被截?cái)啵?/p>
let d = new Date();
// add 12 hours to the date
d.setTime(d.getTime() + (12*60*60*1000));
// truncate the time
d.setHours(0,0,0,0);
console.log(d);

TA貢獻(xiàn)1808條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以檢查小時(shí),如果它在 12 點(diǎn)之前,請(qǐng)將時(shí)間設(shè)置為 00:00:00。如果是 12 點(diǎn)或之后,將時(shí)間設(shè)置為 24:00:00,例如
let d = new Date();
d.setHours(d.getHours() < 12? 0 : 24, 0,0,0);
console.log(d.toISOString() + '\n' + d.toString());

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
//this code will round to the nearest date
const roundToNearestDay = (date) => {
let isPastNoon = date.getHours() >= 12
if (isPastNoon)
//if first parameter > 23, will increment date +1
date.setHours(24,0,0,0)
else
date.setHours(0,0,0,0)
return date
}
let nearestDay = roundToNearestDay(new Date())
console.log(nearestDay)
添加回答
舉報(bào)