Determine minutes until midnight

前端 未结 4 712
不思量自难忘°
不思量自难忘° 2020-12-19 01:58

How would you go about determining how many minutes until midnight of the current day using javascript?

相关标签:
4条回答
  • 2020-12-19 02:15

    You can get the current timestamp, set the hours to 24,

    and subtract the old timestamp from the new one.

    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')

    0 讨论(0)
  • 2020-12-19 02:25

    Here's a one-liner to get milliseconds until midnight

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

    And for the minutes until midnight, we devide that by 60 and then by 1000

    (new Date().setHours(24,0,0,0) - Date.now()) / 60 / 1000
    
    0 讨论(0)
  • 2020-12-19 02:37
    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;
    }
    
    0 讨论(0)
  • 2020-12-19 02:40

    Perhaps:

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

    or

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

    and there is:

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

    0 讨论(0)
提交回复
热议问题