Home Convert datetime-local to UTC time in js/jquery
Reply: 1

Convert datetime-local to UTC time in js/jquery

Rtrader
1#
Rtrader Published in 2017-12-07 22:21:09Z

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!

Felix
2#
Felix Reply to 2017-12-09 02:33:07Z

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.32782 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO