[JS] new Date()를 이용한 초 단위까지 D-day 만들기

Park Bumsoo·2022년 6월 4일
0

D-day

new Date()를 이용하여 D-day 기능을 만들어보자

 const Dday = () => {
    const startDate = new Date();
    const endDate = new Date('2022-06-25');
    const day = startDate.getTime() - endDate.getTime();
    const dday = Math.abs(day / (1000 * 3600 * 24));
    
   return dday;
};


Dday() // 20.625684560185185

위 처럼 간단한 함수로 구현을 할 수있지만
결과값이 딱 떨어지지 않는다.

 const Dday = () => {
    const startDate = new Date();
    const endDate = new Date('2022-06-25');
    const day = startDate.getTime() - endDate.getTime();
    const dday = Math.trunc(Math.abs(day / (1000 * 3600 * 24)));
    
   return dday;
};


Dday() // 20

그래서 위 예제 에서는 Math.trunc()를 사용하여 소수점을 버려주었다.
기능에 따라서 올림 / 내림 / 반올림 Math.ceil() / Math.floor() / Math.round()등의
수학 함수를 사용하여 사용하면 된다 생각한다.

초 단위까지 나타내기

아래 예제와 같이 응용하면 초 단위또한 나타낼 수 있다.

 const Dday = () => {
    const startDate = new Date(); // 2022-06-04T09:18:54.996Z
    const endDate = new Date(1656198000000); // 2022-06-25T23:00:00.000Z
    const day = startDate.getTime() - endDate.getTime();
    const dDay = Math.floor(Math.abs(day / (1000*3600*24)));
    const dHour = Math.floor(Math.abs((day / (1000*3600)) % 24));
    const dMin = Math.floor(Math.abs((day / (1000*60)) % 60));
    const dSec = Math.floor(Math.abs(day / 1000 % 60));
    
   return `${dDay}일 ${dHour}시간 ${dMin}분 ${dSec}초`;
};


Dday() // '21일 13시간 40분 28초'
profile
프론트엔드 주니어 개발자(React, Next.js)

0개의 댓글