JavaScript 날짜 계산법
JavaScript에서 날짜 계산하는 방법을 알아보자.
1.특정 날짜 기준 Date 객체 생성
let now = new Date(); //현재 시간
console.log("지금 날짜 및 시간 => ", now);
//특정일 기준 Date 객체 생성
let now = new Date('2023-04-01'); //특정일 기준
console.log("날짜 및 시간 => ", now);
Date 객체 생성자에 날짜 포맷은 YYYY-MM-DD, YYYY.MM.DD, YYYY*MM*DD 등 몇 가지 구분자 포맷으로 사용가능하지만
관례상 YYYY-MM-DD, YYYY.MM.DD 포멧을 많이 쓰며 YYYYMMDD는 사용할 수 없다.
2. 단순 일수 더하기 월 더하기 (어제, 내일, 며칠전, 며칠 후, 다음달, 이전달, 내년, 전년)
let now = new Date();
let yesterday = new Date(now.setDate(now.getDate()-1)); //Date 객체 기준 1일 전
console.log("1일 전 => ", yesterday);
let now = new Date();
let tomorrow = new Date(now.setDate(now.getDate()+1)); //Date 객체 기준 1일 후
console.log("1일 후 => ", tomorrow);
let now = new Date();
let prevMonth = new Date(now.setMonth(now.getMonth()-1)); //Date 객체 기준 1개월 전
console.log("1개월 전 => ", prevMonth);
let now = new Date();
let nextMonth = new Date(now.setMonth(now.getMonth()+1)); //Date 객체 기준 1개월 뒤
console.log("1개월 후 => ", nextMonth);
※참고로 getMonth() 함수는 현재 월보다 -1이 되어서 나오니 참고하자.
let now = new Date(); //현재 시간
let prevYear = new Date(now.setFullYear(now.getFullYear()-1)); //Date 객체 기준 1년 전
console.log("1개월 전 => ", prevYear);
let now = new Date(); //현재 시간
let nextYear = new Date(now.setFullYear(now.getFullYear()+1)); //Date 객체 기준 1년 뒤
console.log("1개월 후 => ", nextYear);
3. 특정 날짜와 몇일 차이 나는지 구하는법 ( 날짜 비교 )
let now = new Date(); //현재 시간
//특정일 기준 Date 객체 생성
let date = new Date('2023-04-01'); //특정일 기준
const diffDate = Math.floor(Math.abs((now.getTime() - date.getTime())/(1000*60*60*24)))
console.log("날짜 차이 -> ", diffDate );
'Language > JavaScript' 카테고리의 다른 글
script integrity 무결성 오류 [ Failed to find a valid digest in the 'integrity' attribute for resource ] (0) | 2023.12.28 |
---|