Ask Your Question
1

What is the process to obtain the corresponding UTC day using the user's timezone, fromHours, and toHours?

asked 2021-06-09 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-10-15 03:00:00 +0000

bukephalos gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-06-09 11:00:00 +0000

Seen: 11 times

Last updated: Oct 15 '22