3

I have a moment that I want to store in local storage and compare against at a later date using isBefore().

When I stringify this moment it converts it to ISO8601 format, fine. However when I try to bring this string back into play by turning it into a new moment it has a different value. The hour is getting offset by a timezone conversion.

It goes like this:

moment().hour(); = 21

JSON.stringify(moment()); = "2013-05-20T21:38:31.819Z"`

moment("2013-05-20T21:38:31.819Z").hour(); = 22

Obviously the issue here is related to the fact ISO8601 is in UTC format but no matter how I try to use the moment utc() function it doesn't change the fact the fundamental values underneath are different.

How can I stringify a moment and then parse it again with the value remaining contant?

Oliver Lloyd
  • 4,936
  • 7
  • 33
  • 55

1 Answers1

0

The workaround I have for this is to force moment to not use utc when converting the string. So, where foobar is the object sotred in local storage, if:

foobar.expires = 2013-05-22T15:30:23.834Z

then the statement:

moment(foobar.expires, "YYYY-MM-DDTHH:MM:SS.SSS")

will return the same moment that was originally stringify'd when it was stored in local storage.

Messy hack though.

Oliver Lloyd
  • 4,936
  • 7
  • 33
  • 55