13 hours ago

How can I convert UTC time to local unix time?

As part of my React app's survey component, I've incorporated a "skip survey" button. I'd like the survey to reappear n-days (or hours) after the user clicks this button. The backend sends the rejected time in UTC format when the app loads; this is where the problem lies.

To solve the problem, I need to create a function that compares the rejected date in UTC to a locale date (since my users could be from anywhere). If the comparison evaluates to true, the survey component should render.

My biggest challenge is converting the UTC date to Unix (in milliseconds). How can I accomplish this?

const shouldShowSurvey = (rejectedDateUTC, repeatIntervalMs) => {
  // rejectedDateMs is a UTC unix time
  const rejectedDateMs = new Date(rejectedDateUTC).getTime();
  const now = new Date().getTime();

  return rejectedDateMs + repeatIntervalMs < now;

shouldShowSurvey("2023-05-03T13:02:08.107402", 5000);
12 hours ago
Verified Answer
I see. You can convert the UTC date to Unix time in milliseconds by using the Date.parse() method. Here's an example:
const rejectedDateUTC = "2023-05-03T13:02:08.107402";
const rejectedDateMs = Date.parse(rejectedDateUTC);

This will output the following:
You can then use this value to compare with the current time in milliseconds to determine whether the survey component should render. Let me know if you have any other questions!
13 hours ago
The provided function shouldShowSurvey is correct and will work as expected. It converts the rejected date in UTC format to a Unix timestamp in milliseconds and compares it to the current date and time in milliseconds, as returned by new Date().getTime(). If the rejected date plus the repeat interval in milliseconds is less than the current date and time, the function returns true and the survey component should be rendered. To demonstrate, the function is called with a rejected date of "2023-05-03T13:02:08.107402" and a repeat interval of 5000 milliseconds, meaning the survey should appear again 5 seconds after it was skipped.