반응형

 

자바스크립트를 하면서, 엄청나게 많이 사용한다.

7일전으로 설정해주세요.

한달전으로 설정해주세요.

한달후로 설정해주세요.

일년전으로 설정해주세요.등등등. Date 객체를 계속 활용해야하는 경우이다.

그래서 나는 common.js을 만들어, Date 객체에 prototype을 설정해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 현재 년월일에서 일을 +- 일 한 결과 리턴.
Date.prototype.addDays = function (days) {
    var date = this;
    return new Date(date.setDate(date.getDate() + days));
};
 
// 현재 년월일에서 월을 +- 월 한 결과 리턴.
Date.prototype.addMonth = function (month) {
    var date = this;
    return new Date(date.setMonth(date.getMonth() + month));
};
 
// 현재 년월일에서 년을 +- 월 한 결과 리턴.
Date.prototype.addYear = function (year) {
    var date = this;
    return new Date(date.setFullYear(date.getFullYear() + year));
};
cs

해당 prototype을 설정해주면 모든 페이지에서 사용이 가능하다.

사용 방법은 간단하다.

1
2
3
4
5
6
7
8
// 사용방법
new Date().addDays(1);   // 내일
new Date().addDays(-1);  // 어제
new Date().addDays(-7);  // 일주일전
new Date().addMonth(-1); // 한달전
new Date().addMonth(-6); // 6개월전
new Date().addYear(-1);  // 1년전
new Date().addYear(2);   // 2년후
cs

Date 객체를 자주 사용하기 때문에, 해당 함수를 prototype에 등록하여 코드량을 줄여보자.

 

반응형

+ Recent posts