Calendar(달력)


개발을 시작한지 얼마 안되었을때
회사에서 프로젝트를 진행하면서 javascript 달력을 만들었는데
오늘 보니 코드가 아주 더럽다.
좀더 깔끔하게 코드도 바꾸고 기능도 추가해 달력을 구현해 보았다.

먼저 달력구현을 위해 객체를 만들었다.
참고
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date
https://msdn.microsoft.com/ko-kr/library/4d4x3w61(v=vs.94).aspx

Calendar

    

    //Calendar 객체
    function Calendar(newDate){
      if(newDate == null){
        this.date = new Date();
      }
      this.date = newDate;
      this.set = function(newDate) {
        this.date = newDate;
      };
      this.get = function() {
        return this.date;
      };
      this.getLongTime = function() {
        return this.date.getTime();
      };
      this.setLongTime = function(millisec) {
        return this.date.setTime(millisec);
      };
      this.setTxtTime = function(time_txt){
        var time = time_txt.split(":");
        this.date.setHours(time[0]);
        this.date.setMinutes(time[1]);
        this.date.setSeconds(time[2]);
      }
      this.getTxtTime = function(){
        return this.date.setHours() + ":" + this.date.setMinutes() +":" +this.date.setSeconds();
      }
      this.addDay = function( day ) {
        this.setLongTime(this.getLongTime() + day * 86400000);
      }
      this.getYear = function() {
        return this.date.getFullYear();
      };
      this.setYear = function(year) {
        this.date.setFullYear(year);
      };

      this.getMonth = function() {
        return this.date.getMonth()+1;
      };
      this.setMonth = function(month) {
        this.date.setMonth(month-1);
      };
      this.getDayOfMonth = function() {
        return this.date.getDate();
      };
      this.setDayOfMonth = function(dayOfMonth) {
        this.date.setDate(dayOfMonth);
      };

      this.setDayOfWeek = function(dayOfWeek) {
        var day = dayOfWeek - this.date.getDay();
        this.addDay(day);
      };
      this.getDayOfWeek = function() {
        return this.date.getDay();
      };

      this.getLastDay = function(){
        return new Date(this.date.getFullYear(), (this.date.getMonth())+1, 0);
      }
      this.getStartDay = function(){
        return new Date(this.date.getFullYear(), this.date.getMonth(), 1);
      }
      this.setDate = function( year, month, dayOfMonth ) {
        this.setYear(year);
        this.setMonth(month);
        this.setDayOfMonth(dayOfMonth);
      };

      this.getyyyyMMdd = function() { return this.getYear() + "-" + filling(this.getMonth(), 2) + "-" + filling(this.getDayOfMonth(), 2); };

      var filling = function(value, length) {
        var result = "" + value;
        for( var step = result.length; step < length; step++ ) {
          result = "0" + result;
        }
        return result;
      }
    }
    
    

Date 객체

new Date(); new Date(value); new Date(dateString); new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
선언시 주의할 점 1. dateString은 규격이 있는데, 브라우저나 언어에서 이 규격을 따르긴 하는데 구현할 때 차이가 있어서 완~~전! 스트레스를 받는다. 얼마전에도 화면에서 앱으로 date를 넘기면서 앱에서 dateString으로 date를 선언하는 과정에서 버그가 있었다. 개발할 때 주의할 필요가 있겠다. 2. Date는 literal을 지원하지 않아 무조건 new 연산자를 이용해 생성해야한다. 3. 하나이상의 파라미터의 경우 local시를 기반으로 처리 된다. UTC UTC는 협정 세계시로 그리니치 평균시에 기반한다. GMT = 국제원자시 + 윤초(자전 주기가 일정하지 않기 때문에 세계시 UT1과 0.9초의 차이가 생길 때 협정 세계시에서는 하루의 마지막 1분을 59초나 61초로 해서 이 차이를 수정한다.) 메소드 Date객체는 요주의 인물(메소드)들이 몇있는데 얘네를 잘 이해해야 날짜의 지배자가 될 수 있다. (* 알쏭달쏭 주의 *) - value: 기준, 1970년 1월 1일 00:00:00 부터의 시간을 밀리초 단위로 표현한 정수값. 윤초는 무시한다. - getYear : 2018 / 08 / 23 기준 118 이 값으로 반환된다 이 값은 1900을 뺀 값이다.진정으로 원하는 2018 을 얻고 싶다면 getFullYear를 사용해야 한다. - getDay : 요일을 [0-6] 의 수로 반환한다. 주의 할점은! 현지화된 플랫폼에서 다르게 반환 될 수 있는데 우리나라의 경우 0: 일요일 이지만 영국 독일의 경우 0은 월요일을 뜻한다. - getLastDay : 실제로 이런 메소드는 없지만 달력을 구현할 때 필요해서 만들어 두었다. new 를 이용해서 Date를 선언할 때 day 를 0으로 선언하면 전달의 마지막 날이 된다.
예를 들어,
day = [1-31]
new Date(2018, 7, 0) >> 2018.7.31 이 된다.
30일인 달을 선언 할 때 31로 선언하면 다음달의 1일이 된다. (그 달의 첫날은 굳이 이런식으로 알아 낼 필요가 없지만.. )
new Date(2018, 5, 31) >> 2018.7.01
참고로 year = [0-11]
new Date(2018,12,1) >> 2019.01.01 이 된다 변환 date를 string으로 변환하는 방식에는 세가지 방식이 있다. 1. ISO 8601 확장 형식에 따른 변환 >> toISOString() : 2018-08-26T08:52:04.894Z 2. GMT 표준 시간대 기준에 따른 변환 >> toGMTString() : Sun, 26 Aug 2018 08:52:04 GMT 3. 시스템 설정에 근거한 변환(지역에 따라 다름) >> toLocaleString() : 2018. 8. 26. 오후 5:52:04 우리나라는 세계 표준시와 9시간의 차이가 있기 때문에 사용시 주의해야한다. 현재 시간을 string으로 input을 셋팅할때 더욱 유의해야함. (사용자가 수첩을 입력할때 입력한 시간이 자동으로 입력되게 했는데(valueAsDate = date객체 를 사용했었다.), 9시 이전일 경우 전날에 입력한것으로 저장이 되었다. )