javascript 자바스크립트 하루 전/후 날짜 구하기 다음달 이전달 구하기 내년 작년 날짜 구하기
1. 하루 전/후 구하기
[code]
let d = new Date();
let sel_day = -1; //일자를 조절하시면 됩니다. -1이면 하루전/ +1이면 내일
d.setDate(d.getDate() + sel_day );
let year = d.getFullYear();
let month = ('0' + (d.getMonth() + 1 )).slice(-2);
let day = ('0' + d.getDate()).slice(-2);
dt = year+"-"+month+"-"+day;
document.write(dt)
[/code]
2. 다음달 / 이전달 구하기
[code]
let d = new Date();
let sel_month = -1; // 월을 조절하시면 됩니다. -1이면 전달을 +1이면 다음달을..
d.setMonth(d.getMonth() + sel_month );
let year = d.getFullYear();
let month = ('0' + (d.getMonth() + 1 )).slice(-2);
let day = ('0' + d.getDate()).slice(-2);
dt = year+"-"+month+"-"+day;
document.write(dt);
[/code]
3. 작년/내년 구하기
[code]
let d = new Date();
let sel_year = -1; //일자를 조절하시면 됩니다. -1이면 하루전/ +1이면 내일
d.setFullYear(d.getFullYear() + sel_year );
let year = d.getFullYear();
let month = ('0' + (d.getMonth() + 1 )).slice(-2);
let day = ('0' + d.getDate()).slice(-2);
dt = year+"-"+month+"-"+day;
document.write(dt);
[/code]
링크 : https://lifefun.tistory.com/30
댓글 3개
"2022년 1월 31일"에 "다음달"을 구하면, "2022년 3월 3일"이 나옵니다.
"2022년 3월 31일"에 "이전달"을 구하면, "2022년 3월 3일"이 나옵니다.
2월 31일은 없으니까요. 2월 28일에서 초과된 만큼 더해 3월 3일이 나옵니다.
+ Date.prototype.setMonth()
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth
- https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth
결국 "말일"에 대한 처리가 필요합니다.
아래처럼 일 부분을 0으로 지정 시, 전달의 말일을 구할 수 있으니
이 값을 이용해 적당한 처리를 해주면 됩니다. 생략합니다!
let lastday = (new Date(2022, 2, 0)).getDate(); // 월(0~11), 2022년 3월 0일 => 2022년 2월 28일
* PHP에서도 같아요.
게시판 목록
개발자팁
질문은 QA에서 해주시기 바랍니다.
| 번호 | 분류 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|---|
| 4946 | node.js | 6년 전 | 2610 | ||
| 4945 | node.js | 6년 전 | 2382 | ||
| 4944 | node.js | 6년 전 | 2520 | ||
| 4943 | node.js | 6년 전 | 2272 | ||
| 4942 | node.js | 6년 전 | 2250 | ||
| 4941 | node.js | 6년 전 | 2720 | ||
| 4940 | node.js | 6년 전 | 1867 | ||
| 4939 | node.js | 6년 전 | 1995 | ||
| 4938 | node.js | 6년 전 | 2459 | ||
| 4937 | node.js | 6년 전 | 2250 | ||
| 4936 | node.js | 6년 전 | 2322 | ||
| 4935 | node.js | 6년 전 | 2136 | ||
| 4934 | node.js | 6년 전 | 2442 | ||
| 4933 | node.js | 6년 전 | 2247 | ||
| 4932 | node.js | 6년 전 | 2687 | ||
| 4931 | node.js | 6년 전 | 2070 | ||
| 4930 | node.js | 6년 전 | 1999 | ||
| 4929 | node.js | 6년 전 | 8632 | ||
| 4928 | node.js | 6년 전 | 3750 | ||
| 4927 | node.js | 6년 전 | 2394 | ||
| 4926 | node.js | 6년 전 | 2504 | ||
| 4925 | node.js | 6년 전 | 2084 | ||
| 4924 | node.js | 6년 전 | 3374 | ||
| 4923 | node.js | 6년 전 | 2221 | ||
| 4922 | node.js | 6년 전 | 1991 | ||
| 4921 | node.js | 6년 전 | 2046 | ||
| 4920 | node.js | 6년 전 | 1765 | ||
| 4919 | node.js | 6년 전 | 2032 | ||
| 4918 | node.js | 6년 전 | 2180 | ||
| 4917 | node.js | 6년 전 | 2396 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기