RLe
RLe

Reputation: 486

Get GMT time for date and time

I have a string in GMT "2017-01-17 00:00:00.000" and I want to get time and date differently (the string does not have to be in that format). I tried:

var datetime = new Date(calEvent.start);
var date = datetime.toLocaleDateString(); //output: 1/16/2017
var time = datetime.toLocaleTimeString(); //output: 4:00:00 PM

but the output for date and time I want should be in GMT timezone. Anyone know how to do that without using substring for string? Thanks

Upvotes: 0

Views: 932

Answers (1)

RobG
RobG

Reputation: 147413

The string "2017-01-17 00:00:00.000" is not consistent with the subset of ISO 8601 specified in ECMA-262 and will not be parsed correctly in some browsers. As it is, it will be treated as local if parsed at all.

You can modify the string by adding a "T" between the date and time and a trailing "Z" for UTC, then let the Date constructor parse it, e.g.

var s = '2017-01-17 00:00:00.000';
var d = new Date(s.replace(' ', 'T') + 'Z');
console.log(d);

Which will work in most modern browsers, however it will fail in older browsers like IE. You can also write a small function to parse the strting as UTC:

function parseAsUTC(s) {
  var b = s.split(/\D/);
  return new Date(Date.UTC(b[0], b[1] - 1, b[2], b[3], b[4], b[5], b[6]));
  }

console.log(parseAsUTC('2017-01-17 00:00:00.000'));

You can also use one of the various libraries available, however if all you need it to parse one particular format, then that's not necessary.

NOTE:

It's generally not recommended to parse strings with the Date constructor (or Date.parse) as they are largely implementation dependent, however the ISO 8601 extended format is now fairly well supported and is specified in ECMA-262.

The time zone must be specified with upper case "Z". Firefox (at least) will generate an invalid date if "z" is used.

Upvotes: 1

Related Questions