确定距离午夜还有几分钟

Determine minutes until midnight

本文关键字:分钟 几分钟 距离 午夜      更新时间:2023-09-26

如何使用javascript确定距离当前午夜还有多少分钟?

function minutesUntilMidnight() {
    var midnight = new Date();
    midnight.setHours( 24 );
    midnight.setMinutes( 0 );
    midnight.setSeconds( 0 );
    midnight.setMilliseconds( 0 );
    return ( midnight.getTime() - new Date().getTime() ) / 1000 / 60;
}

可能:

function minsToMidnight() {
  var now = new Date();
  var then = new Date(now);
  then.setHours(24, 0, 0, 0);
  return (then - now) / 6e4;
}
console.log(minsToMidnight());

function minsToMidnight() {
  var msd = 8.64e7;
  var now = new Date();
  return (msd - (now - now.getTimezoneOffset() * 6e4) % msd) / 6e4;
}
console.log(minsToMidnight())

function minsToMidnight(){
  var d = new Date();
  return (-d + d.setHours(24,0,0,0))/6e4;
}
console.log(minsToMidnight());

甚至是一行字:

minsToMidnight = () => (-(d = new Date()) + d.setHours(24,0,0,0))/6e4;
console.log(minsToMidnight());

可以获取当前时间戳,将小时设置为24小时,

并从新的时间戳中减去旧的时间戳。

function beforeMidnight(){
    var mid= new Date(), 
    ts= mid.getTime();
    mid.setHours(24, 0, 0, 0);
    return Math.floor((mid - ts)/60000);
}

alert(beforeMidnight()+ ' minutes until midnight')

下面的一行代码用于获取午夜前的毫秒数

new Date().setHours(24,0,0,0) - Date.now()

午夜前的分钟数,除以60再除以1000

(new Date().setHours(24,0,0,0) - Date.now()) / 60 / 1000

将此作为一天中任何时间都有效的替代解决方案。

const timeUntilHour = (hour) => {
    if (hour < 0 || hour > 24) throw new Error("Invalid hour format!");
    const now = new Date();
    const target = new Date(now);
    if (now.getHours() >= hour)
        target.setDate(now.getDate() + 1);
    target.setHours(hour);
    target.setMinutes(0);
    target.setSeconds(0);
    target.setMilliseconds(0);
    return target.getTime() - now.getTime();
}
const millisecondsUntilMidnight = timeUntilHour(24);
const minutesUntilMidnight = millisecondsUntilMidnight / (60 * 1000);