본문 바로가기
개발하는 '정'/JS

javascript 현재 날짜 구하기 / 날짜 더하고 빼기 / date format (YYYY-mm-dd)

by 주앤정_블로그 2023. 10. 17.

javascript 현재 날짜 구하기 / 날짜 더하고 빼기 / date format (YYYY-mm-dd)

 

javascript에는 date 객체의 포맷을 설정할 수 있는 함수가 없다.

그러므로 연/월/일을 각각 구해 계산한 후, 문자열 형태로 원하는 포맷처럼 나열하여 사용해야한다.

 

 

1. 현재 날짜 구하기

 1) 현재 날짜 구하기

let date = new Date(); //Tue Oct 17 2023 09:41:29 GMT+0900 (한국 표준시)

new Date를 사용하면 현재 날짜를 "Tue Oct 17 2023 09:41:29 GMT+0900 (한국 표준시)" 와 같이 구할 수 있다.

 

 

 2) 연/월/일/시간/분/초 각각 구하기

let date = new Date();
console.log("date : "+date); //date : Tue Oct 17 2023 09:43:09 GMT+0900 (한국 표준시)

let year = date.getFullYear();
console.log("year : "+year); //year : 2023

let month = date.getMonth() + 1;
console.log("month : "+month); //month : 10

let day = date.getDate();
console.log("day : "+day); //day : 17

let hour = date.getHours();
console.log("hour : "+hour); //hour : 9

let minute = date.getMinutes();
console.log("minute : "+minute); //minute : 43

let second = date.getSeconds();
console.log("second : "+second); //second : 9

getFullYear, getMonth, getDate, getHours, getMinutes, getSeconds 함수를 이용하여 구할 수 있다.

 

 

2. 날짜 계산

1-2 에서 구한 연/월/일/시/분/초를 이용하여 날짜를 계산할 수 있다.

아래는 월을 계산하는 예시이다.

let month = date.getMonth();
console.log(month); //9

date.setMonth(10);
let val1 = date.getMonth();
console.log(val1); //10

let val2 = date.getMonth() - 3; //10-3
console.log(val2); //7

let val3 = date.getMonth() + 3; //10+3
console.log(val3); //13

date.setMonth(date.getMonth() + 3);
let val4 = date.getMonth();
console.log(val4); //1

월은 0부터 시작한다. 현재가 1월일 때, date.getMonth()를 출력하면 0이 출력된다.

 * setMonth(10) : 월을 10으로 변경한다. (10월)

 * date.getMonth() - 3 : 월에서 3을 뺀다. (10-3 = 7월).

      위의 소스에서는 현재 리얼타임 상의 월에서 3을 빼는 것이 아니라, setMonth로 설정한 값(10)에서 3을 뺀다.

      만약 setMonth를 하지 않았다면, 9-3으로 6이 나온다.

 * date.getMonth() + 3 : 월에서 3을 더한다. (10+3 = 13). 단순하게 값을 더하는 것이므로, 1월로 노출되지 않는다.

 * date.setMonth(date.getMonth() + 3) : 월 + 3 한 값으로 월을 지정한다. (10+3 = 1월)

 

 

동일한 방식으로 함수만 변경하면 연/월/일/시/분/초를 계산할 수 있다.

let date = new Date();

let year = date.getFullYear(); 
console.log('year 변경 전 : ' + year); //year 변경 전 : 2023
date.setFullYear(date.getFullYear()+1); 
year = date.getFullYear();
console.log('year 변경 후 : ' + year); //year 변경 후 : 2024

let month = date.getMonth()+1; 
console.log('month 변경 전 : ' + month); // month 변경 전 : 10
date.setMonth(date.getMonth()+2);
month = date.getMonth();
console.log('month 변경 후 : ' + month); // month 변경 후 : 11

let day = date.getDate(); 
console.log('day 변경 전 : ' + day); // day 변경 전 : 17
date.setDate(date.getDate()-1);
day = date.getDate();
console.log('day 변경 후 : ' + day); // day 변경 후 : 16

let hour = date.getHours(); 
console.log('hour 변경 전 : ' + hour); // hour 변경 전 : 10
date.setHours(date.getHours()+1); 
hour = date.getHours();
console.log('hour 변경 후 : ' + hour); // hour 변경 후 : 11

let minute = date.getMinutes(); 
console.log('minute 변경 전 : ' + minute); // minute 변경 전 : 3
date.setMinutes(date.getMinutes()+10); 
minute = date.getMinutes();
console.log('minute 변경 후 : ' + minute); // minute 변경 후 : 13

let second = date.getSeconds(); 
console.log('second 변경 전 : ' + second); // second 변경 전 : 23
date.setSeconds(date.getSeconds()+10); 
second = date.getSeconds();
console.log('second 변경 후 : ' + second); // second 변경 후 : 3

 

 

3. date format 지정 (YYYY-mm-dd)

 1~2에서 가져온 값을 문자열 형태로 나열하면 된다.

let date = new Date();

let year = date.getFullYear();
date.setMonth(date.getMonth()+1);
let month = date.getMonth();
let day = date.getDate();
let hour = date.getHours();

month = month >= 10 ? month : '0' + month; //m -> mm 형태로 변환
day = day >= 10 ? day : '0' + day; //d -> dd 형태로 변환

console.log(year + '-' + month + '-' + day); //2023-10-17

이때, 월과 일은 한자리 수로 떨어지기 때문에 두자리 수로 변환해주어야한다.

 

 

4. 응용

은행에서 주로 사용하는 3개월 / 6개월 / 1년 전 검색을 구현해보았다.

<input type="text" name="sdate" readonly="true" /> ~ <input type="text" name="edate" readonly="true" />

<button onClick="setDate(3)">3개월</button>
<button onClick="setDate(6)">6개월</button>
<button onClick="setDate(12)">1년</button>

 

function setDate(val) {
    if (val)
    {
        let date = new Date();

        //종료일 (현재)
        date.setMonth(date.getMonth()+1);
        let e_month = date.getMonth();
        let day = date.getDate();
        let hour = date.getHours();
        e_month = e_month >= 10 ? e_month : '0' + e_month;
        day = day >= 10 ? day : '0' + day;

        $("input[name='edate']").val(date.getFullYear() + '-' + e_month + '-' + day);

        //시작일 (현재 - val)
        date.setMonth(date.getMonth()-val);
        let s_month = date.getMonth();
        s_month = s_month >= 10 ? s_month : '0' + s_month;

        $("input[name='sdate']").val(date.getFullYear() + '-' + s_month + '-' + day);
    }
}

 

 

끝.

 

 

 

반응형

 

 

반응형

댓글