1 | initial version |
Assuming you have the date and time in the user's timezone, and you want to obtain the corresponding UTC day within the range of fromHours and toHours:
Example code:
function getUTCDate(userDate, fromHours, toHours) {
// Convert user date to UTC
const utcDate = new Date(userDate.getTime() + (userDate.getTimezoneOffset() * 60000));
// Get UTC day
let utcDay = utcDate.getUTCDate();
// Adjust UTC day if necessary
if (utcDate.getUTCHours() < fromHours || utcDate.getUTCHours() >= toHours) {
if (utcDate.getUTCHours() < fromHours) {
utcDay--;
} else {
utcDay++;
}
}
// Create and return adjusted UTC date
return new Date(Date.UTC(utcDate.getUTCFullYear(), utcDate.getUTCMonth(), utcDay));
}
Example usage:
// Get UTC date for March 31, 2021, 4:30 PM in Pacific Standard Time (UTC-8) with range from 7 AM to 7 PM
const userDate = new Date('2021-03-31T16:30:00-0800');
const utcDate = getUTCDate(userDate, 7, 19);
console.log(utcDate.toISOString()); // Output: 2021-03-31T23:00:00.000Z