Convert specific date and time based on user location for utc date and time

I am working on a JavaScript application. In my application, we created a list from which the user can select the time.

The list looks like this

As soon as the user selects a time from the list, based on today's date, I need to convert the date (which is today's date) and the time selected by the user in UTC.

There are tons of messages that talk about converting dates to UTC, but each has its pros and cons. Some of the posts are old, and JavaScript is evolving every day.

I need to consider the location of users when converting the date. I will assume that ever the location / time zone was set on the user computer as the correct location / time zone.

+5
source share
2 answers

var userTime = new Date(); should give you something like: Sun Dec 27 2015 21:58:08 GMT-0600 (CST) when you call userTime .

You can either do some simple math, or use userTime.toISOString(); and set GMT time for you, for example. "2015-12-28T04:04:07.626Z"

0
source

If you need to find the location, you can use HTML5 geolocation, otherwise the new date wll will return a Date object

You can do this with either .toISOSTring() or with .toUTCString().

 (function(){ var a = new Date(); // Using .toISOSTring document.getElementById('demo').textContent = a.toISOString(); var b =new Date(new Date().toUTCString().substr(0, 25)) document.getElementById('demo1').textContent = b }()) 

WORKING MODEL

EDIT

You can also find the function to return the result in UTC format.

  function convertDateToUTC(date) { return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); } 

WORKING MODEL 2

0
source

Source: https://habr.com/ru/post/1239326/


All Articles