marc2019
marc2019

Reputation: 47

How to localize input from an html datetime-local input

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?

Upvotes: 1

Views: 3922

Answers (2)

Daisy
Daisy

Reputation: 328

(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");

Upvotes: 3

Clive Atkins
Clive Atkins

Reputation: 543

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">

Upvotes: -1

Related Questions