20240808 supabase 시간은 다르게 흐른다?

RingKim1·2024년 8월 8일

TIL

목록 보기
71/77

Today

프로젝트

  • 반응형 웹페이지(모바일 - 채팅)


Learn

TroubleShooting

문제

채팅 메세지를 표시하려는데 현재 시간이랑 맞지 않아서 supabase 테이블을 확인 한 결과
9시간이 차이가 나게 기록

원인

  • 시간대 설정 : 기본적으로 JavaScript의 Date 객체는 UTC를 기준으로 작동
    • 한국 시간(UTC+9) 차이

해결

  • 서버에서 데이터를 가져올 때 클라이언트에서 한국 시간으로 가공
  1. 기존
export const formatDateToHours = (isoDate: number) => {
const date = new Date(isoDate);
const hours = String(date.getUTCHours()).padStart(2, "0");
const minutes = String(date.getUTCMinutes()).padStart(2, "0");

return ${hours}:${minutes};
};

export const formatDateToYears = (isoDate: number) => {
const date = new Date(isoDate);
const year = date.getUTCFullYear();
const month = String(date.getUTCMonth() + 1).padStart(2, "0"); // 월은 0부터 시작
const day = String(date.getUTCDate()).padStart(2, "0");

return ${year}.${month}.${day};
};
  1. 변경
export const formatDateToHours = (isoDate: string): string => {
const localDate = new Date(isoDate);
const options: Intl.DateTimeFormatOptions = { timeZone: "Asia/Seoul", hour: "2-digit", minute: "2-digit" };
return localDate.toLocaleTimeString("ko-KR", options);
};

export const formatDateToYears = (isoDate: string): string => {
const localDate = new Date(isoDate);
const options: Intl.DateTimeFormatOptions = {
timeZone: "Asia/Seoul",
year: "numeric",
month: "2-digit",
day: "2-digit",
};
const formattedDate = localDate.toLocaleDateString("ko-KR", options);

return formattedDate.replace(/./g, ".");
};

정리

  • isoDate라는 ISO형식의 날짜 문자열(예: "2024-08-08T12:00:00Z")
  • 로컬 날짜 변환 : new Date(isoDate)를 사용하여 ISO 날짜 문자열을 Date 객체로 변환
  • options 객체: Intl.DateTimeFormatOptions 타입의 객체
    • timeZone: "Asia/Seoul"로 설정하여 서울의 시간대에 맞춤
    • year: "numeric"으로 설정하여 연도를 숫자로 표시 (예: "2024")
    • month: "2-digit"으로 설정하여 월을 두 자리 숫자로 표시 (예: "08")
    • day: "2-digit"으로 설정하여 일을 두 자리 숫자로 표시 (예: "08")
  • 날짜 문자열 포맷 : toLocaleDateString("ko-KR", options) 메서드를 사용해 한국어 형식으로 변환된 날짜 문자열을 생성
  • 정규표현식 : formattedDate.replace(/./g, ".") 모든 문자를 점(.)으로 대체
    /./g는 정규표현식으로, .는 모든 문자를 의미하며, g 플래그는 전역 검색을 의미

주절주절

나는 미친 사람이다!! 할 수 있다.
다시 다짐해가며 운동을 시작하자

profile
커피는 콜드브루

0개의 댓글