gpt4 book ai didi

javascript - 如何使用 JavaScript 的仅 float 学来计算时间差?

转载 作者:行者123 更新时间:2023-11-28 08:00:23 26 4
gpt4 key购买 nike

目标:获取过去的 Unix 时间值,并以“10h 18m 22s”格式表示其与当前时间的偏移量。

当前代码:

function humaniseTime(epoch) {
nowtime = (new Date).getTime()/1000; // current ms to s
secs = Math.round(nowtime-epoch);

hours = secs/3600;
secs -= hours*3600;

minutes = secs/60;
secs -= minutes*60;

clockstring = hours + "h " + minutes + "m " + secs + "s";
return clockstring;
}

问题是,由于 JavaScript 不使用整数而是使用 float ,所以我最终得到的是 0.564166666 小时,而不是 0h 17m 22s。使用舍入函数会给我带来负数,这不好。

最佳答案

我为您编写了另一个解决方案,该解决方案与您的不同,但工作起来很顺利,代码如下:

function secondsToString(seconds)
{
var numyears = Math.floor(seconds / 31536000);
var numdays = Math.floor((seconds % 31536000) / 86400);
var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;
return numyears + " years " + numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";

}

var epoch = Math.floor(1294862756114/1000); //in your case this will be function argument, converting it into seconds as well
alert("Epoch: " + epoch)
var time = Math.floor((new Date().getTime())/1000);
alert("Current Time: " + time);
var difference = time-epoch;
alert("Difference: " + secondsToString(difference));

这相当简单,希望您在理解它时不会遇到问题。我基本上添加了一个将秒转换为年、月、日、小时数的函数。您现在就可以使用它来保留您需要的任何值。

<强> See the deamo here

关于javascript - 如何使用 JavaScript 的仅 float 学来计算时间差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25503142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com