我想將幾周,幾天和幾小時轉換爲秒,然後再將它們轉換回來。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
這是因爲Math.floor的你使用 – romuleald
@romuleald,抱歉,但不是事實並非如此。 Math.floor在這裏很好。問題在於減少了幾周而沒有將它們轉換回秒。 – MartyB