개발이야기/자바스크립트

[자바스크립트] javascript Date() 함수로 원하는 날짜 추출하기

후린개발자 2022. 9. 6.
반응형

자바스크립트 Date 객체로 원하는 날짜를 가져 올수 있습니다.

converDateString() 함수를 통해서 원하는 날짜 포맷으로도 수정하실수 있습니다.

 

<script>
function addZero(i) {
	var rtn = i + 100;
	return rtn.toString().substr(1, 3);
}
function converDateString(dt) {
	return dt.getFullYear() + "-" + addZero(eval(dt.getMonth() + 1)) + "-"+ addZero(dt.getDate());
}
//today
var now = new Date();
var year = now.getFullYear();
var mon = addZero(eval(now.getMonth()+1));
var day = addZero(now.getDate());
var today = year + "-" + mon + "-" + day;

//weekStart
var now = new Date();
var nowDayOfWeek = now.getDay();
var nowDay = now.getDate();
var nowMonth = now.getMonth();
var nowYear = now.getYear();
nowYear += (nowYear < 2000) ? 1900 : 0;
var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
var weekStart = converDateString(weekStartDate);

//weekEnd
var now = new Date();
var nowDayOfWeek = now.getDay();
var nowDay = now.getDate();
var nowMonth = now.getMonth();
var nowYear = now.getYear();
nowYear += (nowYear < 2000) ? 1900 : 0;
var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
var weekEnd = converDateString(weekEndDate);

//monthStart
var now = new Date();
var year = now.getFullYear();
var mon = addZero(eval(now.getMonth() + 1));
var day = addZero(1);
var monthStart = year + "-" + mon + "-" + day;

//monthEnd
var now = new Date();
var year = now.getFullYear();
var mon = addZero(eval(now.getMonth() + 1));
var day = new Date(now.getYear(),now.getMonth()+1,"").getDate();
var monthEnd = year + "-" + mon + "-" + day;
</script>
반응형

댓글

💲 추천 글