2013-08-02 95 views
6

我需要编写JavaScript,这将允许我比较两个ISO时间戳,然后打印出它们之间的差异,例如:“32秒”。比较2 ISO 8601时间戳和输出秒/分钟差

以下是我在堆栈溢出中找到的函数,它将普通日期转换为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? 
+0

所以你想比较'currentISODateTime'和'ISODateTimeToCompareWith',他们都是ISO 8601格式? – federicot

+0

@Campari是的,就是这样,然后输出它们之间的差异。他们都是ISO 8601格式。 – jskidd3

回答

17

比较两个日期很简单,只要

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 
+0

谢谢。数字之后'e3'是什么意思? – jskidd3

+4

哦,我明白了,我认为它只是60k的捷径。 :P – jskidd3

1

我只是将Date对象存储为ISODate类的一部分。您可以在需要显示字符串时进行字符串转换,例如使用toString方法。你可以用很简单的逻辑与日期类的方法来确定差的两个ISODates之间:

var difference = ISODate.date - ISODateToCompare.date; 
if (difference > 60000) { 
    // display minutes and seconds 
} else { 
    // display seconds 
} 
1

我建议得到时间(秒)从两个时间戳,就像这样:

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的日期在几秒钟内进行比较,以获得它们之间的绝对差异,无论哪个先。

+0

我发现你应该将'(new Date(ISO))。getTime()'除以1000而不是乘以1000来达到以秒为单位的值。 – eskimwier