5

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?

Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
  • [Moment.js](http://momentjs.com/) can help you. [This question](http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript) may also help. – Lars Kotthoff Aug 07 '12 at 15:25
  • Did OP find an answer for this. Facing the same issue. need to figure out if a user submitted datetime string has timezone info pre-built or not. if its not then parsers can select default timezones. – user1101791 Jun 20 '20 at 09:51

2 Answers2

2

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.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
  • 1
    I should have been clearer I guess. It might not always be UTC, I think it could be GMT, or Z, or any other timezone signifier. – Justin Harvey Aug 07 '12 at 15:56
  • @JustinHarvey, then just look for any letter, check the edit. :P – Oleg V. Volkov Aug 07 '12 at 16:15
  • 2
    @OlegV.Volkov: Do you mean to use `/[a-z]/i` as your RegEx? This approach will work for the datetime formats in OP's original question, but fails on a valid ISO 8601 datetime like `"2007-04-05T14:30"` because it matches the `"T"` despite there being no timezone information. – Bill DeRose May 25 '17 at 16:11
1

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)
maerics
  • 151,642
  • 46
  • 269
  • 291