2015-04-30 34 views
0

我有以下的時間跨度從模型來在MVC:如何使用JavaScript來增加時間?

timeTaken = "00:01:00"; 

然後,我有一個乘數

multiply = "3"; 

結果:00:03:00

什麼是最好的方式計算這個時間?

我不知道很多圖書館。我正在考慮把秒,分和小時分開,把每一個分成幾秒鐘,然後把它們重新放在一起。

但是,我有這樣的計算很多部分,它只是似乎有點平凡。我能否以更好的方式乘以時間?

感謝

+4

我說得到了'TimeSpan'總毫秒,乘在您的JS並將其轉換成任何你需要的粒度。 –

回答

3

我結合我在多個頁面中發現的片段。將hh:mm:ss轉換爲秒,乘以3x,然後再轉換爲hh:mm:ss。

var hms = '00:01:00'; // your input string 
var a = hms.split(':'); // split it at the colons 

// minutes are worth 60 seconds. Hours are worth 60 minutes. 
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 
var newSeconds= 3*seconds; 

// multiply by 1000 because Date() requires miliseconds 
var date = new Date(newSeconds * 1000); 
var hh = date.getUTCHours(); 
var mm = date.getUTCMinutes(); 
var ss = date.getSeconds(); 
// If you were building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time 
// if (hh > 12) {hh = hh % 12;} 
// These lines ensure you have two-digits 
if (hh < 10) {hh = "0"+hh;} 
if (mm < 10) {mm = "0"+mm;} 
if (ss < 10) {ss = "0"+ss;} 
// This formats your string to HH:MM:SS 
var t = hh+":"+mm+":"+ss; 
document.write(t); 

JSFiddle

+1

這很好,謝謝。 – DarkShadowAY

1

首先,你可以將它們轉換成秒如下

var hms = "00:01:00"; 
var a = hms.split(':'); // split it at the colons 

// minutes are worth 60 seconds. Hours are worth 60 minutes. 
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 

var newSeconds=seconds * 3; 

var t = new Date(); 
t.setSeconds(newSeconds); 

console.log(t); 

DEMO

更新

爲了獲得剛剛做的時間如下

var time=t.toTimeString().split(' ')[0] 

DEMO

UPDATE

從時間,你可以做如下

t.toTimeString().split(' ')[0].split(':')[0] 

,12小時格式,你可以做,以獲得每小時只獲得小時如下:

var hour; 
if(t.toTimeString().split(' ')[0].split(':')[0]>12) 
    hour=t.toTimeString().split(' ')[0].split(':')[0]-12; 
else 
    hour=t.toTimeString().split(' ')[0].split(':')[0]; 
alert(hour); 

UPDATED DEMO

+0

這是一個很好的做法,我怎麼只寫出時間而不是其他的? – DarkShadowAY

+0

@DarkShadowAY。檢查更新的答案! :) –

+0

@Gurupeasad饒謝謝。經過一些測試,這不是很準確。它關閉了幾分鐘。有沒有辦法省略新時間之前的小時? – DarkShadowAY