Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...