728x90
반응형
JavaScript에서 날짜를 계산하는 방법을 알려드리도록 하겠습니다.
🧨getFullYear()
console.log("[년도출력함수]" + date.getFullYear());
🧨getMonth()
* 참고 : 1월은 0부터 시작 그래서 +1을 해야 현재 월이 됨
console.log("[월 출력 함수]" + date.getMonth());
🧨getDate()
console.log("[날짜 출력 함수]" + date.getDate());
🧨getDay()
* 참고 : 월요일 = 1, 화요일 = 2, 수요일 =3, 목요일 = 4, 금요일 = 5, 토요일 6, 일요일 7
console.log("[요일 출력 함수]" + date.getDay());
let date = new Date();
console.log("[년도 출력함 수]" + date.getFullYear());
console.log("[월 출력 함수]" + date.getMonth());
console.log("[날짜 출력 함수]" + date.getDate());
console.log("[요일 출력 함수]" + date.getDay());
현재 시간 기준으로 getDate 를 통해 날짜를 가져와 다시 setDate를 통해 값을 할당해야 하며 할당 이후 getMonth 함수 사용만 참고해야합니다. getMonth를 사용하면 1월이면 0을 출력하는 구조로 현재 월을 가져오고 싶다면 getMonth + 1 을 해서 사용하시길 바랍니다.
let now = new Date(); // 현재시간
const sYear = now.getFullYear();
const sMonth = (now.getMonth() + 1) < 10 ? "0"+(now.getMonth() + 1) : (now.getMonth()+ 1);
const sDay = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
const sHour = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
const sMinute = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
const sSecond = now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
const applySd = now.getFullYear()+"-"+sMonth+"-"+sDay + " " + sHour + ":" + sMinute + ":" + sSecond;
console.log("[Date now------]", now);
console.log("[Date Full Now]", applySd);
let yesterday = new Date(now.setDate(now.getDate() - 1)); // 어제
console.log("[Date yesterday]", now);
let tomorrow = new Date(now.setDate(now.getDate() + 1)); // 내일
console.log("[Date tomorrow-]", tomorrow);
let oneMonthAgo = new Date(now.setMonth(now.getMonth() - 1)); // 한달 전
console.log("[Date Before One Month]", oneMonthAgo);
let oneMonthLater = new Date(now.setMonth(now.getMonth() + 1)); // 한달 후
console.log("[Date After One Month]", oneMonthLater);
let oneYearAgo = new Date(now.setFullYear(now.getFullYear() - 1)); // 일년 전
console.log("[Date Before One Year]: ", oneYearAgo);
let oneYearLater = new Date(now.setFullYear(now.getFullYear() + 1)); // 일년 후
console.log("[Date After One Year]", oneYearLater);
728x90
반응형
'💚04_HTML5 & Javascript & CSS > 01_Javascript' 카테고리의 다른 글
#removeEventListener #스크롤이벤트체크 #이벤트체크메소드 #약관동의 #스크롤 (0) | 2024.05.23 |
---|---|
#var #let #const #변수 #차이점 #ES6 #스코프 #호이스팅 (0) | 2024.02.22 |
#javascript #함수 #filter #find #구분 (0) | 2023.11.16 |
#window. #window.location #reload #페이지이동 (0) | 2023.11.07 |
#javascript #현재URL #호출 (0) | 2022.12.12 |
댓글