0

I receive the following date from the server:

"2018-11-21 07:00:00 UTC"

Then, I convert it using userTimzone variable (since I wish the editor would use the user timezone):

dateOfAction: moment(dateOfLoss, 'YYYY-MM-DD HH:mm Z').tz(userTimzone).unix(), So dateOfAction is 1542776400. That is: Wednesday, November 21, 2018 5:00:00 AM - and so far so good. That is the dateOfAction in UTC with after right offset

I'm using react-datetime as the calendar the edit the date, using UTC. When performing the save action, without touching the date, the calendar output is still 1542783600, but I wish to be 1542783600 - i.e the same value as in the beginning, reverting the offset at the other direction.

How can I achieve that?

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
Chen
  • 2,958
  • 5
  • 26
  • 45

1 Answers1

0

A few things:

  • Moment doesn't map the Z token to the string "UTC". Since you're parsing in local mode, you are actually getting a moment based on the local computer's time zone rather than UTC. Thus, change the first part of your code to:

    moment.utc(dateOfLoss, 'YYYY-MM-DD HH:mm [UTC]')
    

    The brackets are to treat UTC as a literal string, which isn't strictly required so you can omit it if you like and the result will be the same.

    moment.utc(dateOfLoss, 'YYYY-MM-DD HH:mm')
    
  • There's no need to call .tz(userTimezone) if you're just going to call .unix() subsequently. Unix timestamps are always UTC based. Though it's not clear why you're asking for a Unix timestamp, as react-datetime doesn't need one.

  • The two values you gave in the last paragraph of your question are identical, so I'm not sure specifically what you were looking for. The time you gave is indeed 1542783600, not 1542776400.

  • The readme file of react-datetime describes all the options you can use. You can simply pass the moment object obtained above to the value prop. You might need to use the utc or displayTimeZone props if you want to change the behavior. You might also need to call .local() or .tz(userTimezone) on the moment object before passing it in, but I'm not certain if that is required or not for this particular component.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575