2016-04-29 126 views
-4

我想計算時間差,例如12:30 pm-12:00am,不知道我做錯了什麼。任何指針將不勝感激。使用Javascript計算分鐘差異

function CountingMinutesI(str) { 
 
\t var times = str.split('-'); \t 
 
    \t var from = times[0]; 
 
    \t var to = times[1]; 
 
    
 
function timer(num){ 
 
\t var hrs = num.split(':'); 
 
    \t var min = hrs[1].slice(0,2); 
 
    \t var ampm = hrs[1].slice(2); 
 
    \t var totalMins = 0; 
 
    
 
    \t var pmMins = if (ampm === 'pm'){ 
 
     return 720; 
 
    }else 
 
    \t return 0; 
 
    
 
\t var totalMins = hrs*60 + mins + pmMins ; 
 
    \t return totalMins; 
 
} 
 
    var diff = timer(from) - timer(to); 
 
    \t return diff; 
 
} 
 

 

 
    
 
// keep this function call here 
 
CountingMinutesI("12:30pm-12:00am");

+2

那是沒有辦法打電話。你需要使用'CountingMinutesI(「12:30 pm-12:00am」);' –

+0

只是一個愚蠢的問題什麼是在24小時制12:30下午? –

+3

@NinaScholz 12:30根據[維基百科](https://en.wikipedia.org/wiki/12-hour_clock) –

回答

0

使用Moment.JS

var moment = require('moment'); 

function CountingMinutesI (str) { 
    var timeStrings = str.split('-'); 
    var from = moment(timeStrings[0]); 
    var to = moment(timeStrings[1]); 
    var duration = moment.duration(to.diff(from)); 
    var minutes = duration.asMinutes(); 
    return minutes; 
} 

var diff = CountingMinutesI('12:30pm-12:00am');