'Moment compare the timezoned date, not UTC

I have searched this a number of times and maybe I missed an answer that worked but most I tried ended up comparing UTC in timezone.

I have had a problem recently whereby I am removing events from a calendar by a certain timezone, here is a problem I have run into:

A user viewing in Asia/Seoul time will have time slot on 29 March 8pm UTC appear as 1st April 5am.

The problem I have is when I use something like:

            if (!(
                momentExt.tz(start, timezone).isBefore(to) &&
                momentExt.tz(end, timezone).isAfter(from)
            )) {

It will always compare against UTC, not the actual timezone as such it will return false for this case deleting that calendar event, so I do:

            const startLocalFormat = momentExt.tz(start, timezone).format('YYYY-MM-DDTHH:mm:ss');
            const endLocalFormat = momentExt.tz(end, timezone).format('YYYY-MM-DDTHH:mm:ss');

            if (!(
                momentExt.utc(startLocalFormat, 'YYYY-MM-DDTHH:mm:ss').isBefore(to) &&
                momentExt.utc(endLocalFormat, 'YYYY-MM-DDTHH:mm:ss').isAfter(from)
            )) {

But this feels super hacky. Is there a way to compare the actual timezone dates and not the underlying UTC dates?



Solution 1:[1]

Are you mean you want to remove data base on certain time?

Like you want to remove all data is in 2022-03-01 ~ 2022-03-10 , but it need consider which user timezone is.

The best practice is store time in UTC format (no timezone effect). And then you can do it in this way: (I use date-fns not momment, but it is ok.)

const postDateInZoneTime = format(utcToZonedTime(postDate, 'Asia/Seoul'),'YYYY-MM-DDTHH:mm:ss')
const deleteStartInZoneTime = format(utcToZonedTime(deleteStart, 'Asia/Seoul'),'YYYY-MM-DDTHH:mm:ss')
const deleteEndInZoneTime = format(utcToZonedTime(deleteEnd, 'Asia/Seoul'),'YYYY-MM-DDTHH:mm:ss')

const isDataInTheDeleteTimeRange = isBefore(postDateInZoneTime, deleteStartInZoneTime) && isAfter(postDateInZoneTime, deleteEndInZoneTime)

if(isDataInTheDeleteTimeRange){
// delete data
}

deleteStart & deleteEnd must be UTC time.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JHIH-LEI