I have a dropdown options with local times in starting 12am-11:30pm:
<select>
<option value="12:00am">12:00am</option>
<option value="12:30am"/>12:30am</option>
<option value="1:00am"/>1:00am</option>
<option value="1:30am"/>1:30am</option>
<option value="2:00am"/>2:00am</option>
.....
.....
.....
<option value="11:30pm">11:30pm</option>
</select>
<select>
<option value=this.getUTCVal("12:00am")>this.getUTCVal("12:00am")</option>
.....
.....
.....
<option value=this.getUTCVal("11:30pm")>this.getUTCVal("11:30pm")</option>
</select>
these values are in the array:
var arr=["12:00am","12:30am"....."11:30pm"];
The datepicker that allows to select the date:
the DatePicker
is a react-datepicker- https://www.npmjs.com/package/react-datepicker
<DatePicker
startDate={startDateVal}
endDate={endDateVal} />
I'd like to display an equivalent UTC time for all the values. So I checked resources and most of them uses the standard format of conversion with date.
date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),
date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return new Date(now_utc);
However I dont have a full date and I only can pass times values as arguments to a function. I tried:
getUTCVal(val) {
Math.floor(new Date().getTime() / 1000) // which give me current time
}
I also tried:
var datestring = "1:00";
new Date(datestring); //gives me invalid date
Now I'm not sure how can I convert the time without having the actual date..
Any idea how to fix this?
You will need to get the user selected date as context before converting the user selected time from local to UTC. Then, it is just a matter of creating a Date
object using the user selected date and time so that you can retrieve the UTC time parts with getUTCHours
and getUTCMinutes
.
Below is an example with an arbitrary input date and time (you just need to get the inputDate
and inputHour
values on user selection from your inputs). Also, note that you may need to adjust how the input date is handled based on the data format that is produced by your date picker control.
const getUTCTime = (d) => `${d.getUTCHours()}:${d.getUTCMinutes()} UTC`;
const inputDate = '2018-10-22';
const inputTime = '1:30PM';
const [y, m, d] = inputDate.split('-');
const date = new Date(y, m - 1, d);
let [hh, mm] = inputTime.match(/\d+/g).map((x) => parseInt(x));
let [ap] = inputTime.match(/[a-z]+/i);
ap = ap.toLowerCase()
if (ap === 'pm') {
hh = hh < 12 ? hh + 12 : 0;
}
date.setHours(hh, mm);
console.log(getUTCTime(date));