我需要编写JavaScript,以便比较两个ISO时间戳,然后打印出它们之间的差异,例如:"32秒"。
下面是我在Stack Overflow上找到的一个函数,它将一个普通的日期转换为ISO格式的日期。所以,这是第一件事,获得ISO格式的当前时间。
我需要做的下一件事是获得另一个ISO时间戳,将其与之进行比较,好吧,我将其存储在一个对象中。它可以这样访问:markr.timestamp(如下面的代码所示)。现在我需要比较这两个时间戳,找出它们之间的区别。如果是<60秒,它应该以秒为单位输出,例如,如果它>60秒,则应该在1分12秒之前输出。
谢谢!
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'}
var date = new Date();
var currentISODateTime = ISODateString(date);
var ISODateTimeToCompareWith = marker.timestamp;
// Now how do I compare them?
比较两个日期就像一样简单
var differenceInMs = dateNewer - dateOlder;
因此,将时间戳转换回日期实例
var d1 = new Date('2013-08-02T10:09:08Z'), // 10:09 to
d2 = new Date('2013-08-02T10:20:08Z'); // 10:20 is 11 mins
获取差异
var diff = d2 - d1;
根据需要格式化
if (diff > 60e3) console.log(
Math.floor(diff / 60e3), 'minutes ago'
);
else console.log(
Math.floor(diff / 1e3), 'seconds ago'
);
// 11 minutes ago
我只想将Date对象存储为ISODate类的一部分。您可以在需要显示字符串时进行转换,例如在toString
方法中。这样,您就可以在Date类中使用非常简单的逻辑来确定两个ISODate:之间的差异
var difference = ISODate.date - ISODateToCompare.date;
if (difference > 60000) {
// display minutes and seconds
} else {
// display seconds
}
我建议从两个时间戳中获取以秒为单位的时间,如下所示:
// currentISODateTime and ISODateTimeToCompareWith are ISO 8601 strings as defined in the original post
var firstDate = new Date(currentISODateTime),
secondDate = new Date(ISODateTimeToCompareWith),
firstDateInSeconds = firstDate.getTime() / 1000,
secondDateInSeconds = secondDate.getTime() / 1000,
difference = Math.abs(firstDateInSeconds - secondDateInSeconds);
然后使用difference
。例如:
if (difference < 60) {
alert(difference + ' seconds');
} else if (difference < 3600) {
alert(Math.floor(difference / 60) + ' minutes');
} else {
alert(Math.floor(difference / 3600) + ' hours');
}
重要信息:我使用Math.abs
以秒为单位比较日期,以获得它们之间的绝对差异,无论哪个日期更早