1

I'm trying to convert a GMT time to the user's Local time.

the format of the time i'm getting from the server is : 2015-05-20 18:00:00 GMT

I just want to show hours and minutes like that : 20:00

I wanted to use this solution which seems pretty easy, but I don't know how to make my format same as this

var date = new Date('5/21/2015 18:52:48');
date.toString();
Yasser B.
  • 835
  • 6
  • 20
  • 34

3 Answers3

3

the format of the time i'm getting from the server is : 2015-05-20 18:00:00 GMT

If so, you can easily massage that into a format that ES5 and higher browsers are supposed to support, which would be 2015-05-20T18:00:00Z for your example:

var yourString = "2015-05-20 18:00:00";
var dt = new Date(yourString.replace(' ', 'T') + "Z");
var hours = dt.getHours(); // Will be local time
var minutes = dt.getMinutes(); // Will be local time

Then just format the hours and minutes values you get into your desired hh:mm string.


Note: The Z at the end of the string is important. Unfortunately, the ES5 specification has a significant error in it (they're fixing it in ES6) around what the engine should do if there is no timezone on the string being parsed. Some engines do what the spec says, others do what the spec should have said (and the ES6 spec will say), which unfortunately means that right now, you can't trust what browsers will do if there's no timezone on the string.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-1

I just had to add " UTC "

 var date = new Date('2015-05-20 15:00:00 UTC');
alert(date.getHours());
    alert(date.getMinutes());
Yasser B.
  • 835
  • 6
  • 20
  • 34
  • That date/time format may or may not work in any given browser, as it is not in the specification, and if it *seems* to work, it may or may not actually use UTC as opposed to local time when parsing. I wouldn't rely on it. – T.J. Crowder May 21 '15 at 12:23
-1

new Date() in browser returns date object in user's timezone(machine timezone). Just you need to pass GMT date to Date function in ISO format. So it will treat it as gmt time.

var date = new Date('2015-05-21T18:52:48Z');
date.toString();//You will get here date string in local format

You can also use UTC as UTC and GMT are same.

Here is ex.

var date = new Date('2015-05-21 18:52:48UTC'); //You can use GMT instead UTC
date.toString();//You will get here date string in local format

First method is preferable as second method doesn't work on Internet Explorer

Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65