2010년 8월 31일 화요일

javascript 날짜 계산

몇일부터 몇일까지의 날짜를 계산하기 위한 스크립트

 

-소스

<script type="text/javascript">
var dateUtil = function() {
    this.startObject = null;
    this.endObject = null;
    this.args = null;
}

dateUtil.prototype.formatLen = function(str) {
    return str = (""+str).length<2 ? "0"+str : str;
}

dateUtil.prototype.formatDate = function(dateObject, delimiter) {
    delimiter = delimiter || "-";
    return dateObject.getFullYear() + delimiter + this.formatLen(dateObject.getMonth() + 1) + delimiter + this.formatLen(dateObject.getDate());
}

dateUtil.prototype.toDay = function(delimiter) {
    return this.formatDate(new Date(), "-");
}

dateUtil.prototype.calDate = function() {
    var year = this.args.year == null ? 0 : Number(this.args.year);
    var month = this.args.month == null ? 0 : Number(this.args.month);
    var day = this.args.day == null ? 0 : Number(this.args.day);
    var result = new Date();

    result.setYear(result.getFullYear() + year);
    result.setMonth(result.getMonth() + month);
    result.setDate(result.getDate() + day);
    return this.formatDate(result, "-");
}

dateUtil.prototype.setDate = function(startObject, endObject, args) {
    this.startObject = startObject;
    this.endObject = endObject;
    this.args = args;

    document.getElementById(this.startObject).value = this.calDate()
    document.getElementById(this.endObject).value = this.toDay();
}

var dateUtilObj = new dateUtil();
</script>



-사용

<input type="text" id="startDate" name="startDate" />~
<input type="text" id="endDate" name="endDate" />
<input type="button" value="오늘" onclick="dateUtilObj.setDate('startDate', 'endDate', {})" />
<input type="button" value="7일" onclick="dateUtilObj.setDate('startDate', 'endDate', {day: -7})" />
<input type="button" value="1달" onclick="dateUtilObj.setDate('startDate', 'endDate', {month: -1})" />
<input type="button" value="1년" onclick="dateUtilObj.setDate('startDate', 'endDate', {year: -1})" />

댓글 없음:

댓글 쓰기