javascript 날짜 함수 카테고리 없음2024. 5. 27. 11:13
/**
* numberComma(n)
* 숫자에 콤마 추가함(12345 --> 12,345).
*/
function numberComma(n) {
//-- 정규식
var reg = /(^[+-]?\d+)(\d{3})/;
//-- 숫자를 문자열로 변환
n += '';
while (reg.test(n))
n = n.replace(reg, '$1' + ',' + '$2');
return n;
}
/*yyyyMMdd 형식의 날짜 문자열을 입력 받아 연(year)을 증감한다.*/
function addYear( dateStr, year ) {
dateStr = rmNotNumChar(dateStr);
return addYearMonthDay( dateStr, year, 0, 0 );
}
/*yyyyMMdd 형식의 날짜 문자열을 입력 받아 일(day)을 증감한다.*/
function addDay( dateStr, day ) {
dateStr = rmNotNumChar(dateStr);
return addYearMonthDay( dateStr, 0, 0, day );
}
function addYearMonthDay( source, year, month, day) {
if (isNaN(source) || source.length < 8) {
return "";
}
var yyyy = source.substr(0, 4);
var mm = parseInt(source.substr(4, 2));
var dd = source.substr(6, 2);
var dateStr = new Date(yyyy,(mm-1),dd);
var addDay;
if (year != 0) {
//console.log('@@@ year :: '+year);
addDay = new Date( dateStr.setFullYear( dateStr.getFullYear() + year ) );
}
if (month != 0) {
//console.log('@@@ month :: '+month);
addDay = new Date( dateStr.setMonth( dateStr.getMonth() + month ) );
}
if (day != 0) {
//console.log('@@@ day :: '+day);
addDay = new Date( dateStr.setDate( dateStr.getDate() + day ) );
}
//console.log('@@@ addDay :: '+getDateYMD(addDay));
return getDateYMD(addDay);
}
/* 입력된 date객체를 날짜형식으로 yyyymmdd */
function getDateYMD( source ) {
var now;
if( empty(source) ){
now = new Date();
}else{
now = new Date( source );
}
var year = now.getFullYear();
var month = ("0" + (1 + now.getMonth())).slice(-2);
var day = ("0" + now.getDate()).slice(-2);
return year + month + day;
}
/* 입력된 str객체를 날짜형식으로 YYYY-MM-DD */
function getDateFormatYMD( source ) {
source = rmNotNumChar(source);
if (isNaN(source) || source.length < 8) {
return "";
}
var yyyy = source.substr(0, 4);
var mm = source.substr(4, 2);
var dd = source.substr(6, 2);
var dateStr = new Date(yyyy,(mm-1),dd);
var year = dateStr.getFullYear();
var month = ("0" + (1 + dateStr.getMonth())).slice(-2);
var day = ("0" + dateStr.getDate()).slice(-2);
return year + "-" + month + "-" + day;
}
/* 해당달의 마지막 날짜 구하기 */
function getlastDay( source ) {
source = source.replace(/\D/ig, "");
if (isNaN(source) || source.length < 6) {
return "";
}
var year = source.substr(0, 4);
var month = source.substr(4, 2);
var newDate = new Date(year, month, 0);
var newYear = newDate.getFullYear();
var newMonth = newDate.getMonth()+1;
var newDay = newDate.getDate();
//console.log(newMonth);
if (newMonth.toString().length < 2) newMonth = "0" + newMonth;
if (newDay.toString().length < 2) newDay = "0" + newDay;
return newYear.toString() + newMonth.toString() + newDay.toString();
}