231204 TIL
function getKSTDate() {
const now = new Date();
const kstOffset = 9 * 60; // KST is UTC+9
const utc = now.getTime() + now.getTimezoneOffset() * 60000;
const kstDate = new Date(utc + (kstOffset * 60000));
// Check if the current KST time is before 8:00 AM
if (kstDate.getHours() < 8) {
kstDate.setDate(kstDate.getDate() - 1);
}
return kstDate;
}
위 함수를 실행시키면 다음과 같은 datetime를 반환한다
예) Mon Dec 04 2023 18:23:44 GMT+0900 (Korean Standard Time)
function formatDate(date) {
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
return `${year}.${month}.${day}`;
}
getMonth()
는 Zero-base 로 설정되어있기 때문에 +1을 해줘야 정상적인 해당 달이 출력된다.slice(-2)
)function getLastSevenDays() {
const endDate = getKSTDate();
let dates = [];
for (let i = 6; i >= 0; i--) {
const date = new Date(endDate);
date.setDate(date.getDate() - i);
dates.push(formatDate(date));
}
return dates;
}
const dateList = getLastSevenDays();
Date.prototype.setDate()
: 현재 설정된 월의 시작 부분을 기준으로 Date 객체의 날짜 설정Date.prototype.getDate()
: 주어진 날짜의 현지 시간 기준 일을 반환