22

我需要编写 JavaScript 来比较两个 ISO 时间戳,然后打印出它们之间的差异,例如:“32 秒”。

下面是我在 Stack Overflow 上找到的一个函数,它将普通日期转换为 ISO 格式的日期。所以,这是第一件事,以 ISO 格式获取当前时间。

我需要做的下一件事是获取另一个 ISO 时间戳来比较它,嗯,我已经将它存储在一个对象中。可以像这样访问它:marker.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?
4

3 回答 3

55

比较两个日期很简单

var differenceInMs = dateNewer - dateOlder;

因此,将时间戳转换回Date实例

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
于 2013-08-02T18:44:07.773 回答
1

我只是将 Date 对象存储为 ISODate 类的一部分。您可以在需要显示它时进行字符串转换,比如在toString方法中。这样你就可以对 Date 类使用非常简单的逻辑来确定两个 ISODates 之间的差异:

var difference = ISODate.date - ISODateToCompare.date;
if (difference > 60000) {
  // display minutes and seconds
} else {
  // display seconds
}
于 2013-08-02T18:43:56.400 回答
1

我建议从两个时间戳中获取以秒为单位的时间,如下所示:

// 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以秒为单位比较日期以获得它们之间的绝对差异,无论哪个更早。

于 2013-08-02T18:48:10.867 回答