views:

60

answers:

3

I have this script:

var a="Thu Oct 07 16:50:0 CEST 2010";
var b=a.split("CEST");
var d = new Date(b[0]);
alert(d);​​​​​​​​​​​

But it doesn't work how I want. In fact the date result differs from the original in the string.

The input is Thu Oct 07 16:50:0 CEST 2010 but the result is different Sat Oct 07 2000 16:50:00 GMT+0200 (CEST). What is wrong?

+3  A: 

You're just loosing the information about the year. split splits the string into an array at 'CEST' of which you only parse the first element (the part of the string left of 'CEST'). So you either need to add the right part of the string again or use a better suited method like replace:

var a="Thu Oct 07 16:50:0 CEST 2010";
var b=a.split("CEST");
var d = new Date(b[0]+b[1]);
alert(d);​​​​​​​​​​​

var a="Thu Oct 07 16:50:0 CEST 2010";
var b= a.replace('CEST','');
var d = new Date(b);
alert(d);​​​​​​​​​​​
tec
Of course you are loosing information about the time zone this way and the browser will use your local client side time zone.
tec
Nobody is *loosing* anything - they are, however, **losing** both the year and the timezone.
Stephen P
You are -of course- right, Stephen. I blame the 2 am that we currently have in my time zone for the first typo and my non-native-speaker English skills for the second. ;-)
tec
+1  A: 

As far as I know

  1. :0 in place of :00 is not valid
  2. The year should follow the date e.g. Thu Oct 07 2010 16:50:00 not be at the end
  3. Providing timezone info to be parsed must be in the format GMT(+|-)nnnn for CEST that would be Thu Oct 07 2010 16:50:00 GMT+0200

Though it doesn't really seem to care about the :0

Where did you come up with the string for var a?

Stephen P
+1  A: 

Rearrange the string, replace 'CEST' with the offset time, and parse a date out of it:

var str="Thu Oct 07 16:50:00 CEST 2010",

pattern=str.replace('CEST','GMT-0200').split(' ');
pattern.splice(3,0,pattern.pop());
str=pattern[0]+' '+pattern[1]+' '+pattern[2]+', '+pattern.slice(3).join(' ');

D= new Date(Date.parse(str));

alert('\nLocal: '+D+'\nGMT: '+D.toUTCString())

//Rearranged string: Thu Oct 07, 2010 16:50:00 GMT-02:00

  • Firefox:

    Local: Thu Oct 07 2010 14:50:00 GMT-0400 (Eastern Daylight Time)

    GMT: Thu, 07 Oct 2010 18:50:00 GMT

    IE :

    Local: Thu Oct 7 14:50:00 EDT 2010

    GMT: Thu, 7 Oct 2010 18:50:00 UTC

    Safari:

    Local: Thu Oct 07 2010 14:50:00 GMT-0400 (Eastern Daylight Time)

    GMT: Thu, 07 Oct 2010 18:50:00 GMT

    Opera:

    Local: Thu Oct 07 2010 14:50:00 GMT-0400

    GMT: Thu, 07 Oct 2010 18:50:00 GMT

kennebec