Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

internet explorer - javascript date object issue in Safari and IE

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');

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

In FF and Chrome I get the expected:

Valid Sunday 2 September 2012 ONLY

But in Safari and IE, I get:

Valid undefined NaN undefined NaN ONLY

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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]);

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

EDIT: For a shortcut see answer by joe larson below.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...