javascript 将 UNIX 时间戳差异转换为分钟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17956795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert UNIX timestamp difference to minutes
提问by abpetkov
I have 2 dates, that I convert to UNIX timestamp - start date and confirm date. I subtract one from another and get numbers like these:
我有 2 个日期,我将其转换为 UNIX 时间戳 - 开始日期和确认日期。我从另一个中减去一个并得到这样的数字:
-12643,
0,
3037,
1509,
-3069
-12643,
0,
3037,
1509,
-3069
Basically, what I need to do is to get the difference between the two dates in minutes, but I don't know how to convert those to minutes. The end output should be something like: -25, 13, 155
基本上,我需要做的是以分钟为单位获得两个日期之间的差异,但我不知道如何将它们转换为 minutes。最终输出应该是这样的:-25, 13, 155
回答by Damiaan Dufaux
Given two UNIX timestamps: a, b; you can calculate the difference between them in minutes like this:
给定两个 UNIX 时间戳:a, b; 您可以像这样在几分钟内计算出它们之间的差异:
var a = 1377005400000; //2013-07-20 15:30
var b = 1377783900000; //2013-07-29 15:45
var dateA = new Date(a);
var dateB = new Date(b);
var dayRelativeDifference = dateB.getHours()*60 + dateB.getMinutes()
- dateA.getHours()*60 - dateA.getMinutes();
// dayRelativeDifference will be 15
var absoluteDifference = (b-a)/60
// absoluteDifference will be 12975000
Also have a look at http://www.w3schools.com/jsref/jsref_obj_date.asp
回答by NobleUplift
You just need to divide by 60. You already have the difference between the two timestamps, so none of the Date overhead above is necessary:
你只需要除以 60。你已经有了两个时间戳之间的差异,所以上面的 Date 开销都不是必需的:
var diffs = new Array(-12643, 0, 3037, 1509, -3069);
for (var i = 0; i < diffs.length; i++)
document.write(diffs[i] % 60);
回答by Kamala
How did you get the original numbers? I believe the standard Unix timestamps are in seconds, so you should be able to divide by 60 to get minutes. However, Date.now() in JavaScript, for example, returns milliseconds, so you'd need to divide by 60,000.
你是怎么得到原始数字的?我相信标准的 Unix 时间戳以秒为单位,所以你应该能够除以 60 得到分钟。但是,例如,JavaScript 中的 Date.now() 返回毫秒,因此您需要除以 60,000。