时间以前在Javascript中未定义

我使用下面的函数prettyDate()将时间戳转换为更友好的格式。 我不需要一个插件,它自动将div中的值转换为“Time ago”格式。

一个API返回时间戳14005641661151400695785000date.now()给出1400696094406

使用下面的代码,将第一次时间戳1400564166115转换为2014-05-20T05:36:06.115Z ,其中函数prettyDate()将其转换为Yesterday

对于第二个时间戳, 1400695785000转换为2014-05-21T18:09:45.000Z ,但prettyDate()将其变成undefined 。 另外,在这种情况下day_diff-1diff-14347.209并慢慢地移向0。

为什么它给undefined ,是什么导致day_diff <0

JSfiddle: http : //jsfiddle.net/pWNrS/

 var d = new Date(parseInt(1400564166115)).toISOString() prettyDate(d) // Yesterday var e = new Date(parseInt(1400695785000)).toISOString() prettyDate(e) // undefined *****WHY?***** 

prettyDate()

 prettyDate = function(time){ var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")), diff = (((new Date()).getTime() - date.getTime()) / 1000), day_diff = Math.floor(diff / 86400); if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ) return; return day_diff == 0 && ( diff < 60 && "just now" || diff < 120 && "1 minute ago" || diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" || diff < 7200 && "1 hour ago" || diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days ago" || day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago"; } // If jQuery is included in the page, adds a jQuery plugin to handle it as well if ( typeof jQuery != "undefined" ) jQuery.fn.prettyDate = function(){ return this.each(function(){ var date = prettyDate(this.title); if ( date ) jQuery(this).text( date ); }); }; 

步进prettyDate()

date: Wed May 21 2014 18:35:46 GMT-0400 (EDT)

(new Date())。getTime(): 1400697389253

date.getTime(): 1400711746000

差异: -14356.757

day_diff: -1

这个问题与时区信息的丢失有关。

当你改变ISOstring时,你正在改变被分析date/时间的假设。 在ISO格式中,“Z”表示给出的时间是UTC。 但是,一旦你将其删除,dateparsing器不再有什么时区使用的线索,所以它使用本地时区,并相应地调整时间。 这是什么导致你的diff是负面的(因为你的本地时区偏移量)。

new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ") + ' GMT')可以快速修复在你的date/时间string末尾附加'GMT' new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ") + ' GMT') 。 这是假设所有的date都是UTC / GMT。 但是,如果浏览器支持ES5(例如,你可以testingvar supportsISO8601 = Date.prototype.toISOString === 'function';你可以保持它的ISO8601格式,并将string直接传递给new Date()