Safari和IE中的JavaScript日期对象问题 [英] javascript date object issue in Safari and IE

查看:114
本文介绍了Safari和IE中的JavaScript日期对象问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以2012-12-31的形式从JSON对象收录日期,并尝试将其转换成友好的值并输出。

I am taking a date from a JSON object in the format of 2012-12-31 and trying to convert it into friendly values and output it.

    var redeemableDate = item.Deal.RedeemableDate; //this is coming in the form of 2012-12-31
    var redeemableDate = new Date(redeemableDate);
    var rdDay = weekday[redeemableDate.getDay()]; //using an array with weekdays
    var rdDate = redeemableDate.getDate();
    var rdMonth = monthNames[redeemableDate.getMonth()]; //using an array with month names
    var rdYear = redeemableDate.getFullYear();

    response.write('Valid ' + rdDay + ' ' + rdDate + ' ' + rdMonth + ' ' + rdYear + ' ONLY');

所有这些都可以在Firefox和Chrome中查找和播放,但Safari和IE(仅在IE8上测试远远)不喜欢它。

It all works find and dandy in Firefox and Chrome, but Safari and IE (only tested on IE8 so far) don't like it.

在FF和Chrome中我得到预期的:

In FF and Chrome I get the expected:


有效的星期日2012年9月2日只有

Valid Sunday 2 September 2012 ONLY

但是在Safari和IE中,我得到:

But in Safari and IE, I get:


有效的未定义NaN未定义NaN ONLY

Valid undefined NaN undefined NaN ONLY

当我有一个警报redeemableDate将其设置为Date对象,Safari返回无效日期,IE返回NaN。这显然是问题所在。有没有办法让我的价值成为这些浏览器的日期对象?

When I alert redeemableDate after I have set it as a Date object, Safari returns 'Invalid Date' and IE returns 'NaN'. This is obviously where the issue lies. Is there a way I can get my value into a date object for these browsers?

推荐答案

yyyy-mm-dd 8601)Safari和IE不支持日期格式。它是ECMAscript 5的一部分,所以它应该只是一个时间问题。

The yyyy-mm-dd (ISO 8601) date format is not supported in Safari and IE. It is part of ECMAscript 5 though, so it should be just a matter of time.

解决方案是将日期作为参数传递给Date。

A solution would be to pass the date in as arguments to Date.

var date = "2012-12-31".split("-");
var your_date = new Date(date[0], date[1]-1, date[2]);

请注意,月份参数从零开始(1月份),所以您必须从1从字符串获取的值。

Note that month parameter starts at zero (for January), so you must subtract 1 from the value obtained from the string.

编辑:
有关快捷方式,请参阅下面的joe larson的答案。

For a shortcut see answer by joe larson below.

这篇关于Safari和IE中的JavaScript日期对象问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆