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?
To change the date format on a Mac, click the Apple icon → Click "System Preferences" → Click "Language & Region" → Click "Advanced" → Click "Dates"→ Customize your format.
The JavaScript exception "invalid date" occurs when a string leading to an invalid date has been provided to Date or Date. parse() .
Yes! We're excited to share that a Momentum version of Safari is finally here! If you have any questions or encounter any problems with the Safari version, please contact us.
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.
You're better off parsing the date string yourself:
function dateFromISO( str ) {
var d = null;
str.replace(/^(\d\d\d\d)-(\d\d)-(\d\d)$/, function(_, y, m, d) {
d = new Date(parseInt(y, 10), parseInt(m, 10) - 1, parseInt(d, 10));
});
return d;
}
redeemableDate = dateFromISO( redeemableDate );
Even if the other browsers liked those date strings, you'd have the problem of them always being interpreted as UTC. For me, for example, when I pass that string "2012-12-31" to Firefox, it tells me that the date is 30 Dec 2012, because I'm 6 hours behind UTC. In other words, "2012-12-31" is interpreted as midnight of that date, UTC time. Assuming you want everybody in the world to see the right date, if you construct the Date object with numbers it's assumed to be local time at the client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With