calebo
calebo

Reputation: 3432

Date format YYYY-MM-DD not working in Safari

I have this problem with Safari not recognizing the date format 2012-01-03 (being 2012 January 3rd). I have the dates within an array and then I want to convert them to this format - Tuesday Jan 3

Works in Chrome, but Safari is throwing undefined undefined NaN.

Some code below...

(function() {
    var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
        months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
    Date.prototype.getDayName = function() {
        return days[this.getDay()];
    };
    Date.prototype.getMonthName = function() {
        return months[this.getMonth()];
    };
})();

var issues = ['2012-01-03', '2012-01-02', '2012-01-01', '2011-12-31'];

for (var i = 0; i < issues.length; i++) {
      var d = new Date(issues[i]);
      var date = d.getDate(),
      weekday = d.getDayName(),
      month = d.getMonthName();
      day = weekday + ' ' + month + ' ' + date;               
      $('.datepicker').find('ul').append('<li class="issue_' + i + '">' + day + '</li>');
}   

I only need this to work for Safari/Mobile Safari, so prefer not to use any js library.

Upvotes: 1

Views: 3896

Answers (2)

epascarello
epascarello

Reputation: 207501

Simple debugging shows you the error:

var d = new Date(issues[i]);
console.log(d);

It does not like the date format. You can change it something like this:

var issues = ['01/03/2012', '01/02/2012', '01/01/2011', '12/31/2011'];

or you can do a split and do it in a format all browsers support

var dateParts = issues[i].split(/-/);
var d = new Date(dateParts[0],parseInt( dateParts[1], 10) -1,dateParts[2]);

http://jsfiddle.net/TveJU/

Upvotes: 2

elijah
elijah

Reputation: 2924

Date parsing in the various browsers is notoriously inconsistent and finicky. I've always used Datejs (http://www.datejs.com/), a nice little js library that augments the built-in Date object. Check it out.

Upvotes: 0

Related Questions