2015-09-21 59 views
1

我想將幾周,幾天和幾小時轉換爲秒,然後再將它們轉換回來。JS星期,幾小時和幾秒到幾秒..再回來

當我將它們轉換回來,天數和小時不正確:

var weeks = 3, 
days = 5, 
hours = 1; 

//convert to seconds 
sec_in_w = weeks * 604800, 
sec_in_d = days * 86400, 
secs_in_h = hours * 3600, 
secs = sec_in_w + sec_in_d + secs_in_h; 

//convert back to weeks, days, and hours 
new_w = Math.floor(secs/604800); 
secs -= new_w; 
new_d = Math.floor(secs/86400); 
secs -= new_d; 
new_h = Math.floor(secs/3600); 

console.log('weeks: ' + new_w); 
console.log('days: ' + new_d); 
console.log('hour: ' + new_h); 

DEMO:

http://codepen.io/anon/pen/avZwBp

+0

這是因爲Math.floor的你使用 – romuleald

+0

@romuleald,抱歉,但不是事實並非如此。 Math.floor在這裏很好。問題在於減少了幾周而沒有將它們轉換回秒。 – MartyB

回答

3
//convert back to weeks, days, and hours  
new_w = Math.floor(secs/604800); 
secs = secs % 604800; 
new_d = Math.floor(secs/86400); 
secs = secs % 86400; 
new_h = Math.floor(secs/3600); 

使用模給人的剩餘減去周的天數。

2

你減去周,天數,而不是秒數在幾周或幾天內。

secs -= new_w * 604800; 
new_d = Math.floor(secs/86400); 
secs -= new_d * 86400; 
0

你必須從秒

//convert to seconds 
    sec_in_w = weeks * 604800, 
    sec_in_d = days * 86400, 
    secs_in_h = hours * 3600, 
    secs = sec_in_w + sec_in_d + secs_in_h; 

codepen

0

讓我們來看看發生了什麼這裏: 在行:

secs = sec_in_w + sec_in_d + secs_in_h;

你是在3周內+5天+ 1小時,或

secs = 2250000;

秒增加值

然後你按604800來劃分,你應該得到3,然後你從這個大的值減去這個3 ECS :)。你可以自己算一算:

(2250000 - 3)/86400 = 26

你得到什麼:)同爲小時。

解決方案是先將您的數字轉換回其表示形式,以秒爲單位。

//convert back to weeks, days, and hours 
new_w = Math.floor(secs/604800); 
secs -= new_w * 604800; 
new_d = Math.floor(secs/86400); 
secs -= new_d * 86400; 
new_h = Math.floor(secs/3600); 

順便說一句,JavaScript有處理dates的解決方案。如果你這樣做了練習,我什麼也沒有說當然:)的

相關問題