Ask Your Question

Revision history [back]

click to hide/show revision 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:

  1. Convert the user's date and time to a UTC date and time using the timezone offset.
  2. Extract the day from the UTC date and time.
  3. If the hour component of the UTC date and time is less than fromHours or greater than or equal to toHours, adjust the date by adding or subtracting one day.
  4. Return the adjusted UTC date.

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