2011-12-21 67 views
4

您將如何確定當前使用JavaScript的當天午夜之前多少分鐘?確定分鐘直到午夜

+0

也許這篇文章可以幫助你: http://stackoverflow.com/questions/5847165/jquery- get-difference-between-dates- – 2011-12-21 00:24:47

+0

根據客戶端計算機的午夜時間,或者根據發送給客戶端的服務器JS? – JesseBuesking 2011-12-21 00:26:22

+0

@JesseB:服務器時間,它用於控制檯腳本 – 2011-12-21 00:33:08

回答

6
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

我建議kennebeck's或RobG的答案。只是不要重複自己,我給與問題解釋的鏈接:http://stackoverflow.com/a/15792909/139361 – Dan 2013-04-03 17:34:32

+1

考慮使用'midnight.setHours(24,0,0,0)' – rabudde 2015-01-27 20:22:12

4

你可以得到當前時間戳,設定小時至24

和減去新一舊的時間戳。

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

警報(午夜之前()+ '分鐘,直到午夜')

7

也許:

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());