1

I used a standard html datetime-local input like <input type="datetime-local" />, I put in a time of February 16th, 6 pm from my pc in the EST GMT-5 timezone. From another pc in the same timezone I display the date stored in DB from the input, but it shows February 16th, 1 pm instead of 6 pm. I know this is a timezone problem because there is a 5 hour difference and im in GMT-5. How would I convert the users input to UTC time based on their local time, then store it the db as a UTC time?

EDIT: I did new Date(...).toUTCString() on my server instead of on my client, does this have anything to do with the timezone problem?

1
  • 1
    Post an example of how the date and time were “put in” and how it was converted to a Date and time stamp for display. Commented Feb 17, 2021 at 1:19

2 Answers 2

3

(1) the data we get from datetime-local input is like this

const startTime = "2021-08-28T09:00"

There is no timezone.

The MDN link here: datetime-local

(2): When we send the data to the server (the server timezone may different in different environment) and save in the DB(normally always in UTC timezone) we need to make sure we send the right date time. Convert it to UTC time before sending to server.
We can do:

let result = new Date(startTime);
result.toISOString();

It converts to UTC. Then it will save in the DB as UTC. Link here: toISOString()

(3): We get the UTC data from DB, when it display on the FrontEnd, we need to convert to our local timezone and right format as below.

 this.startTime = moment(this.startTime).format("YYYY-MM-DDTHH:mm");
Sign up to request clarification or add additional context in comments.

Comments

-1

Info here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

<input type="hidden" id="timezone" name="timezone" value="-05:00">

4 Comments

It might help OP more if you'd explain how it works.
Clients wont just be in the GMT-5 timezone so this won't work.
Have you stored the clients timezones in your database?
I convert to a utc date on the frontend, and send it over to the backend which saves it in a mongodb database, the time is still 5 hours off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.