JS周,小时和天到秒......再回来

时间:2015-09-21 11:04:24

标签: javascript datetime

我正在尝试将数周,日和小时转换为秒,然后再将它们转换回来。

当我将它们转换回来时,日期和时间都不正确:

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

样本:

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

4 个答案:

答案 0 :(得分: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);

使用模数给出余数。

答案 1 :(得分:2)

您要减去周数和天数,而不是几周或几天中的秒数。

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

答案 2 :(得分: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

答案 3 :(得分:0)

让我们看看这里发生了什么: 在该行:

secs = sec_in_w + sec_in_d + secs_in_h;

您要在3周+ 5天+ 1小时的秒数内添加值,或

secs = 2250000;

然后你按604800进行搜索,然后得到3,然后从secs :)的大值中减去3。你可以自己做数学:

(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的解决方案。如果你正在做这个练习,我当然没有说:)