views:

51

answers:

3

For some reason, the SOAP response from one of my WebService looks like this:

2010/07/08 04:21:24.477

Where the date format is (YYYY/MM/DD) and the time is GMT

I'm not really sure how to convert this to local time because the format is so odd

+1  A: 

Date.parse should actually parse most of the date string into its respective timestamp.

The 2 caveats appear to be:

  • Milliseconds aren't supported, so they have to be separated and added after parsing.
  • It'll assume local time, so 'GMT' or 'UTC' should to be appended before parsing.

With these in mind, the following should work:

function parseSoapDate(dateString) {
  var dateParts = dateString.split('.'),
      dateParse = dateParts[0],
      dateMilli = dateParts[1];

  return new Date(
    Date.parse(dateParse + ' GMT') +
    parseInt(dateMilli, 10)
  );
}

var date = parseSoapDate('2010/07/08 04:21:24.477');

As for UTC to local time, JavaScript's Date objects should already handle that for you as they can report the date in both UTC and the user's local timezone. You specify which you want by the name of the method (whether it has UTC in it or not):

alert(date.toString());     // local time
alert(date.toUTCString());  // UTC time
Jonathan Lonowski
A: 

This should work:

var dateStr = "2010/07/08 04:21:24.477";
var d = new Date(dateStr.split('.')[0]);
d.setUTCHours(0);
Eric Wendelin
"2010/07/08 04:21:24.477" is not a valid date format.
Anax
Fixed. Did work on Chrome at least.
Eric Wendelin
A: 

It looks like the response of the date/time is in ISO format, which is a sensible way to provide date information.

Suppose that the date returned is 7-8-2010. Would this be the 8th of July or the 7th of August? Having the date in ISO format (YYYY/MM/DD) solves this ambiguity.

You can convert this date to the required format in many different ways, i.e.

var input = '2010/07/08 04:21:24.477';
var now = new Date(input.slice(0, input.indexOf('.')));
alert(now.toLocaleString());

You may want to search the Internet for the Date object or to find snippets which will allow you to convert a date using many different formats.

Anax