我渲染这个JSON对象:
[{"created_at":"2010-09-21T20:41:28Z","subject":"hello world"}]
然后我使用这个日期解析器来解析它(见下文),但它只适用于Chrome 6.0.4,Firefox 3.6.8,但不适用于Safari 5.0.2 ---我收到NaN错误。是什么给了什么?
Date.prototype.toRelativeTime = function(now_threshold) {
var delta = new Date() - this;
now_threshold = parseInt(now_threshold, 10);
if (isNaN(now_threshold)) {
now_threshold = 0;
}
if (delta <= now_threshold) {
return 'Just now';
}
var units = null;
var conversions = {
millisecond: 1, // ms -> ms
second: 1000, // ms -> sec
minute: 60, // sec -> min
hour: 60, // min -> hour
day: 24, // hour -> day
month: 30, // day -> month (roughly)
year: 12 // month -> year
};
for (var key in conversions) {
if (delta < conversions[key]) {
break;
} else {
units = key; // keeps track of the selected key over the iteration
delta = delta / conversions[key];
}
}
// pluralize a unit when the difference is greater than 1.
delta = Math.floor(delta);
if (delta !== 1) { units += "s"; }
return [delta, units, "ago"].join(" ");
};
/*
* Wraps up a common pattern used with this plugin whereby you take a String
* representation of a Date, and want back a date object.
*/
Date.fromString = function(str) {
return new Date(Date.parse(str));
};
答案 0 :(得分:4)
问题是Date
构造函数对ISO 8601的支持并不存在于所有Web浏览器中。您可以执行以下操作:
Date.prototype.setISO8601 = function (string) {
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
this.setTime(Number(time));
}
那么您的代码可能如下所示:
var d = new Date("2010-09-13T11:51:50.9418504+02:00");
if (isNaN(d)) {
//alert("Date constructor not support ISO8601!");
d = new Date();
d.setISO8601("2010-09-13T11:51:50.9418504+02:00");
}
代码不是来自我。我在互联网上找到了它,但我找不到原始来源。
答案 1 :(得分:1)
我想在第一个答案中添加一些词语:
首先,答案是完美的。我希望有人可以告诉我更多有关其来源的信息?
其次,正则表达式中存在一些错误:
我更正了正则表达式,除了第三点(因为没有时间进行测试):
var regexp = "^([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):?([0-9]{2})))?)?)?)?$";
答案 2 :(得分:0)
Tue, 21 Sep 2010 20:06:45 UTC +00:00
是一个人类可读的表示形式,ActiveSupport永远不会使用该格式将日期转换为JSON,除非你修改它(但不推荐)。
但是,您可以使用config.active_support.use_standard_json_time_format
选项toggle the standard json time format。
如果true
,Rails将使用类似XML的日期表示。否则,它将使用自定义格式。
这是源代码
class Time
def as_json(options = nil) #:nodoc:
if ActiveSupport.use_standard_json_time_format
xmlschema
else
%(#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
end
end
end