Marina Marina - 3 months ago 18
Javascript Question

Use JavaScript to convert a date string with timezone to a date object in local time

The format of my date string looks like this:
yyyy-MM-ddTHH:mm:ss-0Z00

example 1:
2010-03-05T07:03:51-0800

example 2:
2010-07-01T20:23:00-0700

I need to create a date object using these date strings.

new Date()
does not work on this string.
Please help me convert these date strings into a date objects with the local timezone.

Thank you!

Edit: I am using this in Pentaho Data Integration 4.3.0.

Answer

You can use a library such as Moment.js to do this.

See the String + Format parsing.

http://momentjs.com/docs/#/parsing/string-format/

The following should parse your date you provided, but you may need to modify it for your needs.

var oldDate = "2010-03-05T07:03:51-0800";

var dateObj = moment(oldDate, "YYY-MM-DDTHH:mm:ssZ").toDate();

Alternatively, see Moment's String parser, which looks like it is in the format you provided, with the exception of a space between the seconds of the time and the time zone.

http://momentjs.com/docs/#/parsing/string/

Alternative

A second way of doing this is Date.js, another library that seems to parse the format just fine. http://www.datejs.com