Skip to content

fix: adjust start & end of event when system timezone is using DST #1222

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions apps/calendar/src/hooks/timezone/useEventsWithTimezone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { createEventCollection } from '@src/controller/base';
import { useTZConverter } from '@src/hooks/timezone/useTZConverter';
import type EventModel from '@src/model/eventModel';
import { primaryTimezoneSelector } from '@src/selectors/timezone';
import TZDate from '@src/time/date';
import { isUsingDST } from '@src/time/timezone';
import type Collection from '@src/utils/collection';
import { clone } from '@src/utils/object';

Expand All @@ -17,6 +19,7 @@ export function useEventsWithTimezone(events: Collection<EventModel>) {
return events;
}

const isSystemUsingDST = isUsingDST(new TZDate());
Copy link
Contributor Author

@adhrinae adhrinae Jul 22, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isUsingDST 는 두 번째 인자로 타임존 이름을 넣지 않을 경우 현재 시스템을 기준으로 해당 시간의 DST 적용 여부를 결정합니다.

이를 통해 브라우저가 DST 적용중인지 아닌지 확인할 수도 있고, 어떤 이벤트가 시스템 타임존 기준으로는 DST 적용을 받고 있는지 아닌지 확인할 수 있습니다.

const {
timedEvents = createEventCollection(),
totalEvents = createEventCollection(),
Expand All @@ -26,8 +29,30 @@ export function useEventsWithTimezone(events: Collection<EventModel>) {

timedEvents.each((eventModel) => {
const clonedEventModel = clone(eventModel);
clonedEventModel.start = tzConverter(primaryTimezoneName, clonedEventModel.start);
clonedEventModel.end = tzConverter(primaryTimezoneName, clonedEventModel.end);

let zonedStart = tzConverter(primaryTimezoneName, clonedEventModel.start);
let zonedEnd = tzConverter(primaryTimezoneName, clonedEventModel.end);

// Adjust the start and end time to the system timezone.
if (isSystemUsingDST) {
if (!isUsingDST(zonedStart)) {
zonedStart = zonedStart.addHours(1);
}
if (!isUsingDST(zonedEnd)) {
zonedEnd = zonedEnd.addHours(1);
}
} else {
if (isUsingDST(zonedStart)) {
zonedStart = zonedStart.addHours(-1);
}
if (isUsingDST(zonedEnd)) {
zonedEnd = zonedEnd.addHours(-1);
}
}

clonedEventModel.start = zonedStart;
clonedEventModel.end = zonedEnd;

totalEvents.add(clonedEventModel);
});

Expand Down
5 changes: 3 additions & 2 deletions apps/calendar/src/time/timezone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function calculateTimezoneOffset(timezoneName: string, targetDate: TZDate
'Intl.DateTimeFormat is not fully supported. So It will return the local timezone offset only.\nYou can use a polyfill to fix this issue.'
);

return -targetDate.getTimezoneOffset();
return -targetDate.toDate().getTimezoneOffset();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TZDategetTimezoneOffsetDategetTimezoneOffset 과 약간 다른데, 이 때문에 문제가 제대로 해결되지 않고 있었습니다. 그래서 시스템의 타임존을 정확하게 꺼낼 필요가 있기 때문에 toDate 로 전환을 해 주었습니다.

}

validateIANATimezoneName(timezoneName);
Expand Down Expand Up @@ -63,7 +63,8 @@ export function isUsingDST(targetDate: TZDate, timezoneName?: string) {
}

return (
Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset()) !== targetDate.getTimezoneOffset()
Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset()) !==
targetDate.toDate().getTimezoneOffset()
);
}

Expand Down
84 changes: 84 additions & 0 deletions apps/calendar/stories/e2e/week.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { h } from 'preact';

import moment from 'moment-timezone';

import { mockWeekViewEvents } from '@stories/mocks/mockWeekViewEvents';
import type { CalendarExampleStory } from '@stories/util/calendarExample';
import { CalendarExample } from '@stories/util/calendarExample';

import type { EventObject } from '@t/events';

export default { title: 'E2E/Week View' };

const Template: CalendarExampleStory = (args) => <CalendarExample {...args} />;
Expand Down Expand Up @@ -170,6 +174,86 @@ DaylightSavingTimeTransitionSouthern.args = {
},
};

// NOTE: For manual testing purposes
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

시스템의 타임존을 모킹하는 동작이 자동화된 테스트 환경에서는 어려웠기 때문에 직접 테스트용 페이지를 작성하여 확인했습니다.

const timezoneNameForSystemTimezoneTest = 'US/Pacific';
// const timezoneNameForSystemTimezoneTest = 'Asia/Seoul';
export const SystemTimezoneTest = Template.bind({});
SystemTimezoneTest.args = {
...Template.args,
options: {
...Template.args.options,
useFormPopup: false,
timezone: {
zones: [
{
timezoneName: timezoneNameForSystemTimezoneTest,
},
],
},
},
onInit: (cal) => {
const convert = (d: Date) =>
moment
.tz(
moment([
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds(),
]).format('YYYY-MM-DD HH:mm:ss'),
timezoneNameForSystemTimezoneTest
)
.toISOString();

cal.setDate('2022-03-09T00:00:00Z');

cal.createEvents([
{
id: 'pst',
title: 'PST',
start: '2022-03-09T09:00:00Z', // 01:00 UTC-08, 18:00 UTC+09
end: '2022-03-09T10:00:00Z', // 02:00 UTC-08, 19:00 UTC+09
},
{
id: 'pdt',
title: 'PDT',
start: '2022-03-16T08:00:00Z', // 01:00 UTC-07, 17:00 UTC+09
end: '2022-03-16T09:00:00Z', // 02:00 UTC-07, 18:00 UTC+09
},
]);

cal.on('selectDateTime', (info) => {
const startDate = info.start;
const endDate = info.end;

cal.createEvents([
{
id: Date.now().toString(32).slice(0, 8),
title: 'New Event',
start: convert(startDate),
end: convert(endDate),
category: 'time',
},
]);

cal.clearGridSelections();
});

cal.on('beforeUpdateEvent', ({ event, changes }) => {
const zonedChanges = Object.keys(changes).reduce<EventObject>((acc, _k) => {
const key = _k as keyof EventObject;
acc[key] = convert(changes[key]);

return acc;
}, {});

cal.updateEvent(event.id, event.calendarId, zonedChanges);
});
},
};

export const CustomTemplate = Template.bind({});
CustomTemplate.args = {
...Template.args,
Expand Down