Reputation: 947
I have a form that a user can input a datetime
<input class="form-control" name="aution_end_time" required type="datetime-local id="auction_end_time-input">
Now what I would like to do is convert this "local datetime object" to UTC time and store that value in a hidden input of the form.
<input type="hidden" class="form-control" name="auction_end_time_utc">
How would I go about this? To summarize: user enters a datetime in the form, then once they do that the hidden input gets updated with the same datetime but in UTC. I am unsure of how to determine the users local time zone and how to convert to UTC. Thanks!
Upvotes: 5
Views: 10074
Reputation: 2358
Or one line of javascript:
const inputEl = document.getElementByName('aution_end_time');
const isoDatetimeStr = (new Date(inputEl.value)).toISOString();
Upvotes: 2
Reputation: 1606
I would recommend to use moment.js for that.
See my code snippet! I changed type="hidden"
to type="text"
and name
to id
for the second input for presentational purpose.
document.getElementById("auction_end_time-input").oninput = function() {
var datetimeLocal = document.getElementById("auction_end_time-input").value;
var datetimeUTC = moment.utc(datetimeLocal).format();
document.getElementById("auction_end_time_utc").value = datetimeUTC;
}
<!-- moment.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment-with-locales.min.js"></script>
<input class="form-control" name="aution_end_time" required type="datetime-local" id="auction_end_time-input">
<input type="text" class="form-control" id="auction_end_time_utc">
Upvotes: 3