새소식

Front

[javascript] 오픈소스를 사용하여 쉽게 날짜 구하기

  • -
728x90


안녕하세요. 말랑고양입니다.


프로젝트를 진행하는 도중 날짜를 구해야되는 일이 있어 포스팅하게 되었습니다.


현재 날짜로부터 15일 전의 날짜를 YYYYMMDD 형식으로 가져와야 했습니다.


아래와 같은 소스코드를 사용하면 쉽게 구할 수 있습니다.


MIT 라이센스가 걸려있는 moment.js를 사용하였습니다.


다른 방법도 있겠지만, 개인적으로 자바스크립트로 날짜를 구할때는 moment.js 이용을 추천드립니다 ^  ^


1
2
3
4
5
6
7
8
9
10
11
12
<script type="text/javascript" src="./moment.js"></script>
<script>
 
    var today = new Date();
    var formattedDate = moment(today).format('YYYYMMDD');
    alert(formattedDate);
 
    var pastday = new Date(Date.parse(today) - 15 * 1000 * 60 * 60 * 24); //현재 날짜 및 시간 
    var formattedPastDate = moment(pastday).format('YYYYMMDD');
    alert(formattedPastDate);
 
</script>
cs


도움이 되셨다면 '공감' 한 번씩 눌러주세요 ^  ^

추가로 궁금한 점이 있으시다면 댓글 남겨주세요. 감사합니다. 


Moment.js is freely distributable under the terms of the MIT license.

#reference : https://momentjs.com/


moment.js

example.html


반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.