0

I've a problem related to timezones.

We are saving logs in our app but we have to show the date in a local date time.

So, for example:

User A saved a log and the database registered this: 2020-09-23T20:22:18.7926625

If I transform that time, it is 8:22 (1 hour above mine), what should I do to transform that date to my current time zone, so it can be desplayed as 7:22

Loui
  • 21
  • 3
  • 2
    Try importing moment.js. It’s very useful –  Sep 24 '20 at 01:00
  • I normally convert the client side time to UTC before submitting to the server. That way it can be converted back with js built-in `Date()` or with a library like moment.js as @chewie suggested. Basically you want the time to always be in UTC (or preferred standard) in the DB and convert it to the local time zone wherever it may be displayed. – Cody Pace Sep 24 '20 at 01:10
  • You should save as a timestamp, then `SELECT UNIX_TIMESTAMP(timestamp)*1000 WHERE condition` and pass that to JavaScript `new Date(here)`. Just make sure you have your time set correctly on the Server. Sometimes you don't have access to the Server time. In those cases *(at least in PHP)* you can use `date_default_timezone_set('America/Vancouver');` before any headers are sent, then INSERT with prepared statements using `time()`, which must be bound to a variable. – StackSlave Sep 24 '20 at 01:20
  • Also, it'll be helpful to use IS0 8601 date format `YYYY-MM-DDThh:mm:ssZ` as JS will see this format and convert it to your local time zone automatically when a new `Date()` object is created. – Cody Pace Sep 24 '20 at 01:23
  • 1
    Just adding here to inform you that MomentJs is no longer the recommended library. While it is still the most functional one, there are other alternatives that can be used to replace MomentJs. Here's the writing on why by MomentJs themselves: https://momentjs.com/docs/#/-project-status/ – Elbert Bae Sep 24 '20 at 01:28
  • @CodyPace thanks for your answer, but I'm doing this: new Date( new Date('2020-09-24T09:46:52.7594894').toISOString() ) and this is returning one hour ahead of the one that I get when I do new Date().getHours() – Loui Sep 24 '20 at 13:50
  • 1
    Hi Luis. Please read [*How do I ask a good question?*](https://stackoverflow.com/help/how-to-ask) and [*How to create a Minimal, Reproducible Example*](https://stackoverflow.com/help/minimal-reproducible-example) from the help center. Then either [edit your question](https://stackoverflow.com/posts/64038122/edit) or ask a new one. In particular, please add code to your question, and tell us whether that code is running on the client or the server. Be sure to tell us what you expected vs what the actual results were. Thanks. – Matt Johnson-Pint Sep 24 '20 at 17:30

1 Answers1

-1

This article from 2014 might provide a solution, or if you need continuous timezone conversion this article may help; otherwise, I'd just try adding on -1:00 to the end

Broski-AC
  • 739
  • 6
  • 12