Search code examples
javascripttimezonedate-fns

How to get the correct start and end of the day in local timezone when the server is on UTC in JavaScript?


I've got server that run the on UTC timezone, but I need to get data range on local timezone, the data have collectTime attribute that has unix timestamp. So I just need to get the start and end of day of the locale to get correct data represent this day

This is what I tried :

const { startOfDay, endOfDay, getTime, subDays } = require("date-fns");
const { utcToZonedTime } = require("date-fns-tz");

const timezone = "Asia/Jakarta";

const correctLocalStartDate = 1685379600000;
const correctLocalEndDate = 1685465999999;

const selectedUnixTime = subDays(new Date(), 1).getTime();

const localDate = utcToZonedTime(selectedUnixTime, timezone);

const localStartDate = getTime(startOfDay(localDate));
const localEndDate = getTime(endOfDay(localDate));

console.log(
  {
    isItCorrect: localStartDate === correctLocalStartDate,
    correctDate: new Date(correctLocalStartDate),
    systemDate: new Date(localStartDate),
  },
  "Start Date"
);

console.log(
  {
    isItCorrect: localEndDate === correctLocalEndDate,
    correctDate: new Date(correctLocalEndDate),
    systemDate: new Date(localEndDate),
  },
  "End Date"
);

Will return

{
  isItCorrect: false,
  correctDate: 2023-05-29T17:00:00.000Z,
  systemDate: 2023-05-30T07:00:00.000Z
} // Start Date

{
  isItCorrect: false,
  correctDate: 2023-05-30T16:59:59.999Z,
  systemDate: 2023-05-31T06:59:59.999Z
} // End Date

But the localStartDate (printed on systemDate) are still wrong since it's not on the correct start of local date that I'm using. How do I get the correct unix timestamp for start and end day on locale date time?


Solution

  • Seems like the original answer has been deleted, I dont know why. But the answer is :

    The endOfday and startOfDay doesn't use timezone date (it's always UTC, because my server are on UTC). The correct way to use it would be :

        const localStartDate = getTime(
          zonedTimeToUtc(startOfDay(localDate), timezone)
        );
        const localEndDate = getTime(zonedTimeToUtc(endOfDay(localDate), timezone));