0

I have a Date Time which is saved on the server in UTC format.

The date is returned to the client looks like this: 2015-02-05T07:52:27.59

I need a javascript function which parses the date string, and converts it to the local time of the client.

Example, the javascript should add 2 hours to specified time, because the client is on on UTC +2.

I have tried many examples on the internet but non of them was working.

I expect to be something easy, considering that this is happening all over the internet.

Catalin
  • 11,503
  • 19
  • 74
  • 147

2 Answers2

1

Split the string, zero reference the month, use Date.UTC when creating the new Date object. The output toString is local time unless you specify something else.

var dateTime = '2015-02-05T07:52:27.59',
    parts = dateTime.split(/[-T:\.]/g);

parts[1] -= 1;
document.body.textContent = new Date(Date.UTC.apply(null, parts)).toString();

Alternatively, if you have a modern browser. Append Z to the string and rely on the Date parse of the particular browser.

var dateTime = '2015-02-05T07:52:27.59Z';

document.body.textContent = new Date(dateTime).toString();
Xotic750
  • 22,914
  • 8
  • 57
  • 79
0

Just append 'UTC' to the string:

var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

Convert UTC date time to local date time using JavaScript

Community
  • 1
  • 1
Phate01
  • 2,499
  • 2
  • 30
  • 55
  • The date format i have is not valid if i add 'UTC' at the end `new Date("2015-02-05T07:52:27.59 UTC")` is invalid – Catalin Feb 05 '15 at 08:24
  • How do you create the Date Time object? – Phate01 Feb 05 '15 at 08:38
  • I'm thinking that the toString() method automatically convert it, because I alerted the date and I get GMT + 1 (instead of GMT, which equals to UTC) – Phate01 Feb 05 '15 at 08:48
  • Seems that .toString() automatically converts it if it contains the magical "Z" – Catalin Feb 05 '15 at 09:12
  • For me it alerts `Thu Feb 05 2015 07:52:27 GMT+0200 (GTB Standard Time` while it should be 09:52:27 o'clock – Catalin Feb 05 '15 at 09:18
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/70292/discussion-between-phate01-and-raraitul). – Phate01 Feb 05 '15 at 09:19