Justin Harvey
Justin Harvey

Reputation: 14672

Test if a string has timezone in javascript

I receive a date time as a string from the server that might look like this:

07/08/2012 13:17:32

This is a UTC time.

Or it might have timezone in format:

07/08/2012 13:17:32 UTC+01:00

I need a general way to parse this into a Date object for display. If I do a var d = new Date(str) then the first example it assumes is a local time.

Edit: It might not always be 'UTC' in the string, I think it could be GMT, or Z, or any other timezone signifier.

Any ideas?

Upvotes: 5

Views: 3087

Answers (2)

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

If your timezone is always in format UTC+nn, and strings with explicit UTC TZ are parsed correctly, as I assume from your question, then simple

if (date_string.search(/a-z/i) == -1) {
 date_string += 'UTC+00:00'
}

will do.

Upvotes: 2

maerics
maerics

Reputation: 156434

As a quick and dirty solution, it looks like the timezone is a final "part" of the format separated by whitespace. So you could count the number of "parts" in the input string and add a default timezone if none is found. For example:

function parseDateDefaultUTC(str) {
  var parts = str.split(/\s+/);
  return new Date((parts.length===3) ? str : str + ' UTC');
}
var d;
d = parseDateDefaultUTC("07/08/2012 13:17:32");
d; // => Sun Jul 08 2012 07:17:32 GMT-0600 (MDT)
d = parseDateDefaultUTC("07/08/2012 13:17:32 UTC+01:00");
d; // => Sun Jul 08 2012 06:17:32 GMT-0600 (MDT)

Upvotes: 1

Related Questions