【发布时间】:2015-04-23 23:23:58
【问题描述】:
我试图从彼此中减去两次,并且在大多数情况下有效,但在某些情况下它给出了错误的输出。
到目前为止,这是我的代码:
//postDateTime looks like 2015-04-23T22:23:32.902Z
//Split the date and time
var postDateTime2 = postDateTime.split("T");
//remove the Z from the post time stamp
postDateTime2[1] = postDateTime2[1].replace('Z','');
//split the post date/time into sperate variables
var postDate = postDateTime2[0]; // date
var postTime = postDateTime2[1]; // time
//split up the post time into hours, minutes, seconds
var postTimeSplit = postTime.split(":");
var postTimeHour = postTimeSplit[0];
var postTimeMinutes = postTimeSplit[1];
var postTimeSeconds = postTimeSplit[2];
//split the date to have year, month, date separate
var postDateSplit = postDate.split("-");
//split the post date to year, month, date
var postYear = postDateSplit[0]; //year
var postMonth = postDateSplit[1]; //month
var postDate2 = postDateSplit[2]; //date
//get the current hour, minutes, seconds in UTC time.
var hours = now.getUTCHours();
var minutes2 = now.getUTCMinutes();
var seconds2 = now.getUTCSeconds();
//get the difference in years between post time and response time
var responseYear = Math.abs(now.getUTCFullYear() - postYear);
//get the difference in months between post time and response time
var responseMonth = Math.abs(mm - postMonth);
//get the difference in days between post time and response time
var responseDate = Math.abs(now.getUTCDate() - postDate2);
//get the difference in hours between post time and response time
var responseHour = Math.abs(now.getUTCHours() - postTimeHour);
//get the difference in minutes between post time and response time
var responseMinutes = Math.abs(now.getUTCMinutes() - postTimeMinutes);
//get the difference in seconds between post time and response time
var responseSeconds = Math.abs(now.getUTCSeconds() - postTimeSeconds);
Math.round(responseSeconds); // round the seconds to up to 2 decimal (doesn't work as expected)
就像我说的,它可以工作,但如果时差超过一小时,它就会开始给出奇怪的输出。例如,如果实际时差只有 38 分钟,而当前时间提前一个小时,则将其计为 1 小时 22 分钟。
有什么建议可以让我做得更好吗?
【问题讨论】:
-
为了更好地解释问题,看这个例子:2015-04-23 23:33:17 - 2015-04-23 23:23:49 = 它给出的输出是 10 分钟和 32.005 秒,但实际上是 0:09:28
-
不要拆分字符串,而是使用Date 函数来获取您需要的部分。可能更容易的是使用
.getTime()获取毫秒刻度并对两个整数进行简单的差分,然后从毫秒确定整个时间单位。 -
Jasen,我可以为当前日期/时间执行此操作,但我想从中减去它的日期/时间被格式化为 RFC 3339 时间戳,我无法更改它。也许我可以在那个 RFC 3339 时间戳中转换我的当前时间,然后减去它们?
-
您可以将该字符串解析为日期:
new date("2015-04-23T22:23:32.902Z")
标签: javascript