views:

40

answers:

2

I've been stuck on this for quite a while and would appreciate some help if possible.

Basically I receive a date from an API in the format yyyy-mm-dd. Amongst other things, I wish to display the weekday. Here is the relevant code:

// jsonDate is in the format yyyy-mm-dd 

var splitDate = jsonDate.split("-");
var joinedDate = splitDate.join(",");      

var myDate = new Date(joinedDate);

var weekday=new Array(7);
weekday[0]="Sun";
weekday[1]="Mon";
weekday[2]="Tue";
weekday[3]="Wed";
weekday[4]="Thu";
weekday[5]="Fri";
weekday[6]="Sat"; 

var dayOfTheWeek = weekday[myDate.getDay()];

Everything works as it should in Firefox, but in IE8 "dayOfTheWeek" is undefined. IE Developer tools also shows "myDate" as "NaN" when I console log it.

Any help would be really appreciated.

A: 

Create the date that way:

var myDate = new Date(splitDate[0],splitDate[1]-1,splitDate[2]);

Date expects the parts as single arguments, not as a formatted string.

There is also a option to pass a string, for example:

MonthAsString Day , year hours:minutes:seconds

but I think you better not use this, it might depend on the javascript-version, which format would be accepted.

Dr.Molle
@Dr.Molle: Since the format is know, I too would have used `new Date(year,month-1,day)`. But the argument can be a string: ECMA-262, 15.9.3: `new Date ([string|number|[year[, month[, date[, hours[, minutes[, seconds[, ms]]]]]]]])`. If the value is a string it is parsed like `Date.parse(value)` and it accepts several different formats but standard allows for implementation-specific heuristics to determinate the format. FF, Chrome, Opera but not IE accepts `YYYY-MM-DD` (international). All of them accepts `M/D/YYYY`.
some
Additional note: None of them produces the same result on `.toString`: FF3.6: `WWW MMM DD YYYY hh:mm:ss GMT+hhmm`, Opera10: `WWW, MMM DD YYYY hh:mm:ss GMT+hhmm`, Chrome 6: `WWW MMM DD YYYY hh:mm:ss GMT+hhmm (text)`, IE8: `WWW MMM D hh:mm:ss UTC+hhmm YYYY`.
some
Awesome, thank you very much Dr.Molle.
Jez
A: 
function dstring(str){
    //yyyy-mm-dd
    str= str.split(/\D+/);  
    str[1]-= 1;
    try{
        var d= new Date();
        d.setHours(0,0,0,0);
        d.setFullYear.apply(d, str);
    }
    catch(er){
        return 'Bad date-'+str;
    }
    return d;
}

dstring('2010-10-21')

/*  returned value: (Date)
Thu Oct 21 2010 00:00:00 GMT-0400 (Eastern Daylight Time)
*/
kennebec