const d = new Date();
// 날짜를 정하기
new Date(2020, 0, 1).toLocaleDateString();
// "2020. 1 1."
const year = d.getFullYear(); // 년
const month = d.getMonth(); // 월
const day = d.getDate(); // 일
// 어제 날짜 구하기
new Date(year, month, day - 1).toLocaleDateString();
// 일주일 전 구하기
new Date(year, month, day - 7).toLocaleDateString();
// 한달 전 구하기
new Date(year, month - 1, day).toLocaleDateString();
// 일년 전 구하기
new Date(year - 1, month, day).toLocaleDateString();
new Date() 안에 넣어서 날짜를 구하는 이유는 8월 1일에서 -7을 할 때 날짜를 7월 25일로 잡아주기 때문입니다.
다른 방식
new Date().setDate(15); // 15일
// -------------
const day = 15;
new Date().setDate(day - 1); // 14일
const month = 3;
new Date().setMonth(month - 1); // 2월
const year = 2021;
new Date().setYear(year - 1); // 2020년
이 방식은 setDate, setMonth, setYear 메서드를 이용한 방식입니다.
위 코드의 첫째줄 Date 객체에는 이제 15일로 바뀌게 됩니다.
만약 day가 15 일시 day - 1을 하면 Date 객체는 하루 전 날인 14일로 바뀌게 됩니다.
setMonth (월) setYear (년) 메서드도 각 월, 년에 해당합니다.
const d = new Date();
// 오늘날의 년, 월, 일 데이터
const day = d.getDate();
const month = d.getMonth();
const year = d.getFullYear();
// 어제 날짜 구하기
new Date(new Date().setDate(day - 1)).toLocaleDateString();
// 일주일 전 구하기
new Date(new Date().setDate(day - 7)).toLocaleDateString();
// 한달 전 구하기
new Date(new Date().setMonth(month - 1)).toLocaleDateString();
// 일년 전 구하기
new Date(new Date().setYear(year - 1)).toLocaleDateString();
만약 어제의 날짜를 구하려면 현재 일 데이터 "getDate" 메서드를 이용하여 구한 뒤 현재의 날에서 하루를 뺀 -1을 해준 값으로 어제의 날짜를 구할 수 있습니다.
추가 자료
[JS] 현재 날짜, 시간 포맷 (YYYY-MM-DD hh:mm:ss)
다양한 방법으로 date format을 할 수 있습니다. 첫 번째 코드 (YYYY-MM-DD hh:mm:ss) new Date(+new Date() + 3240 * 10000).toISOString().replace("T", " ").replace(/\..*/, ''); // 2021-08-05 09:51:31 해당..
gurtn.tistory.com
[JS] 달력 만들기
css의 display의 grid 속성을 이용한 방식입니다. 완성본 포스팅 기준 달 2021년 04월의 달력입니다. 실행 코드 See the Pen by bolgang13 (@bolgang13) on CodePen. 코드 풀이 // 날짜 변환 함수 (년, 월, 일을..
gurtn.tistory.com