2

I have the following string that I implicitly know is in UTC timezone: 2008-03-09 18:02:29

How can I use moment.js to convert it to an object in my local timezone?

I tried the following but it doesn't adjust the time for my local timezone:

> moment("2008-03-09 18:02:29 UTC").format('YYYY-MM-DD HH:mm:ss zz')
"2008-03-09 18:02:29"

PS. I live near Washington DC (UTC -4). But this needs to work properly for any user from anywhere in the world.

I can do it without moment.js like this (but it only works in Chrome, not FF):

new Date('2008-03-09 18:02:29 UTC');

So what's the moment.js code analogous to this??

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272
  • 1
    Have you tried this http://stackoverflow.com/questions/29220467/how-to-convert-moment-js-date-to-users-local-timezone?rq=1 – Jasen Mar 30 '16 at 19:22

2 Answers2

5

You know that you have a UTC date, so you are going to want to parse in UTC mode. After that, use Moment's .local() function to get back to the time of the current user.

moment.utc('2008-03-09 18:02:29').local().format()
"2008-03-09T13:02:29-05:00"

I am in -5, and as you can see, the date was pushed back five hours.

Maggie Pint
  • 2,432
  • 1
  • 11
  • 15
  • Maggie Pint has the correct answer it seems. But note that the result can be surprising. I live in Switzerland and we changed to daylight saving time last Sunday (March 27th), so we live now in UTC+2. But the result of Maggie’s code on my computer is `2008-03-09T19:02:29+01:00`. But this is correct, because at this date we were in UTC+1. – nico Mar 30 '16 at 20:27
0

With moment timezone

moment("2008-03-09 18:02:29 UTC").tz('America/New_York'); // => EST
Wainage
  • 4,892
  • 3
  • 12
  • 22
  • FYI, I live in Washington, but someone else who accesses this website may live anywhere in the world. How do I make it convert to the local time for that browser?? (Sorry if I was unclear in the original question). I'm looking for something analogous to `new Date('2008-03-09 18:02:29 UTC');` – Saqib Ali Mar 30 '16 at 19:39