Skip to content

CHICPRO

  • Life Log
  • Cycling Log
  • Photo Log
    • Portrait
    • Landscape
    • Flower
    • Etc
  • Coding Log
  • Information

PHP로 달력 만들기

2011-12-22 by 편리

달력이라는 게 어려운 것 같지는 않은데.. 아니다 지금 내게는 모든 것이 어렵지.. ㅋ 암튼 작업 중인 사이트에
필요해서 어제 몇시간 혼자 머리 싸매고 수많은 시행착오를 겪은 끝에 드디어 원하는 스타일의 달력을 만들어
낼 수 있었다. 머리 속으로 생각할 때는 그리 어렵지 않았는데 막상 작업하려고 하니 왜 이렇게 어려운 건지…

style.css

#CalendarBox { position: absolute; top: 9px; left: 9px; width: 229px; height: 202px; border: 1px solid #ccc; }
#CalendarBox #calendarTop { position: absolute; top: 19px; left: 16px; width: 196px; height: 26px; }
#CalendarBox #calendarTop .prev_button { position: absolute; top: 4px; left: 45px; width: 5px; height: 10px; cursor: pointer; }
#CalendarBox #calendarTop .next_button { position: absolute; top: 4px; right: 36px; width: 5px; height: 10px; cursor: pointer; }
#CalendarBox #calendarTop .today_button { position: absolute; top: 0; right: 3px; width: 23px; height: 17px; cursor: pointer; }
#CalendarBox #calendarTop #month { position: absolute; top: 2px; left: 50px; width: 105px; text-align: center; font-weight: bold; }
#CalendarBox #calendarTop #month .l_text { color: #000; font-size: 14px; }
#CalendarBox #calendarTop #month .s_text { color: #a6a6a6; font-size: 11px; }
#CalendarBox #Calendar { position: absolute; top: 47px; left: 16px; width: 196px; }
#CalendarBox #Calendar th { width: 28px; height: 13px; text-align: center; font-size: 10px; font-family: Tahomo; color: #000; background: #ededed; }
#CalendarBox #Calendar .sunday { color: #c92727; }
#CalendarBox #Calendar .satday { color: #1f87c7; }
#CalendarBox #Calendar td { height: 17px; padding: 3px 0 0 6px; font-weight: bold; font-size: 10px; color: #000; }
#CalendarBox #Calendar td div { width: 16px; height: 14px; padding-top: 2px; text-align: center; cursor: pointer; }
#CalendarBox #Calendar td div:hover { text-decoration: underline; }
#CalendarBox #Calendar td div.selected { color: #fff; background: #ff6d09; }
#CalendarBox #Calendar td div.outrange { color: 828282; font-weight: normal; }

calendar.php

<?php
$temp = explode(“-“, $date);
$time = strtotime($date);
$first = $temp[0] . “-” . $temp[1] . “-01”;

$str_month = date(“M”, $time);
$week_first = date(“w”, strtotime($first));

$num_month = (int)$temp[1];
$num_year = $temp[0];

$cnt = $day = 0;

$day_id = $temp[0] . “-” . $temp[1];

$prev_month = date(“Y-m-01”, strtotime(“-1 month”, $time));
$next_month = date(“Y-m-01”, strtotime(“+1 month”, $time));

$endday = array(1=>31, 28, 31, 30 , 31, 30, 31, 31, 30 ,31 ,30, 31);
// 윤년 계산 부분이다. 4년에 한번꼴로 2월이 28일이 아닌 29일이 있다.
if( $yyyy%4 == 0 && $yyyy%100 != 0 || $yyyy%400 == 0 )
    $endday[2] = 29; // 조건에 적합할 경우 28을 29로 변경

// 이전, 다음 달 시작 날짜
$prev_temp = explode(“-“, $prev_month);
$prev_idx = (int)$prev_temp[1];
$prev_last = $endday[$prev_idx];
$prev_last_date = substr($prev_month, 0, 8) . $prev_last;
$prev_last_time = strtotime($prev_last_date);
$prev_week_last = date(“w”, strtotime($prev_last_date));
$prev_day = date(“d”, strtotime(“-{$prev_week_last} days”, $prev_last_time));

$next_day = 1;
?>
<div id=”calendarTop”>
    <div id=”cm_<?=$prev_month?>” class=”prev_button ch_month”><img src=”<?=$g4[admin_img_path]?>/calendar_prev_month.png” alt=”” /></div>
    <div id=”month”><span class=”l_text”><?=$num_month?></span> <span class=”s_text”><?=$str_month?>. <?=$num_year?></span></div>
    <div id=”cm_<?=$next_month?>” class=”next_button ch_month”><img src=”<?=$g4[admin_img_path]?>/calendar_next_month.png” alt=”” /></div>
    <div id=”cm_<?=date(“Y-m-d”)?>” class=”today_button ch_month”><img src=”<?=$g4[admin_img_path]?>/calendar_today.png” alt=”오늘” /></div>
</div>
<div id=”Calendar”>
    <table cellpadding=”0″ cellspacing=”0″ border=”0″>
    <tr>
        <th class=”sunday”>S</th>
        <th>M</th>
        <th>T</th>
        <th>W</th>
        <th>T</th>
        <th>F</th>
        <th class=”satday”>S</th>
    </tr>
    <?php
    for($i = 0; $i < 6; $i++) {
        if($day < $endday[$num_month]) {
            echo “<tr>n”;
        }

        for($k = 0; $k < 7; $k++) {
            if($cnt >= $week_first) {
                $day++;
                $day1 = zerofill($day, 2);

                if($day <= $endday[$num_month]) {
                    if($k == 0) {
                        echo “<td><div id='{$day_id}-$day1′ class=’sunday’>$day</div></td>n”;
                    } else if($k == 6) {
                        echo “<td><div id='{$day_id}-$day1′ class=’satday’>$day</div></td>n”;
                    } else {
                        echo “<td><div id='{$day_id}-$day1′>$day</div></td>n”;
                    }
                } else {
                    // 다음 달 일부
                    $next_day_id = substr($next_month, 0, 7) . “-” . zerofill($next_day, 2);

                    if($k == 0) {
                        echo “<td><div id='{$next_day_id}’ class=’outrange sunday’>$next_day</div></td>n”;
                    } else if($k == 6) {
                        echo “<td><div id='{$next_day_id}’ class=’outrange satday’>$next_day</div></td>n”;
                    } else {
                        echo “<td><div id='{$next_day_id}’ class=’outrange’>$next_day</div></td>n”;
                    }

                    $next_day++;

                }
            } else {
                // 이전 달 일부
                $prev_day_id = substr($prev_month, 0, 8) . $prev_day;

                if($k == 0) {
                    echo “<td><div id='{$prev_day_id}’ class=’outrange sunday’>$prev_day</div></td>n”;
                } else {
                    echo “<td><div id='{$prev_day_id}’ class=’outrange’>$prev_day</div></td>n”;
                }

                $prev_day++;
            }

            $cnt++;
        }

        echo “</tr>n”;

        if($day >= $endday[$num_month]) {
            break;
        }

    }
    ?>
    </table>
</div>

<script type=”text/javascript”>
var date;
$(function() {
    $(‘#Calendar div#<?=$date?>’).addClass(“selected”);

    $(‘#Calendar div’).click(function() {
        $(‘#Calendar div’).removeClass(“selected”);
        $(this).addClass(“selected”);

        date = $(this).attr(“id”);
        loadMemo(date);

        if($(this).hasClass(“outrange”)) {
            loadCalendar(date);
        }
    });

    $(‘.ch_month’).click(function() {
        date = $(this).attr(“id”).replace(“cm_”, “”);
        loadMemo(date);
        loadCalendar(date);
    });
});
</script>

zerofill 함수

function zerofill($number,$n) {
    return str_pad((int) $number,$n,”0″,STR_PAD_LEFT);
}

코드는 달력에서 날짜를 클릭하면 해당 일의 메모를 입력할 수 있는 기능 중에 일부분이다. jQuery를 이용해 메모
기능은 작동하도록 구현을 했다. table 과 td를 사용한 것이 지금 마음에 걸리는데.. 시간을 내서 ul 과 li 를 사용하는
방법으로 바꿔볼까 생각 중이다. 그리고 이전 달과 다음 달의 일부분이 출력되는 부분을 좀 더 보강해야할 것 같다.
예를 들어 첫날이 일요일이라면 이전 달의 7일이 표시가 되어야 하는데 지금은 그게 되지 않는다. 이건 또 어찌해야
할런지.. ㅋ 대략적인 구상은 있으니까 작업을 하면 되지 않을까 싶다. 이거 참 쉬운 게 하나도 없다. ㅋㅋ

덧, 참 코드가 지저분한 것 같다. 변수명 하나 짓는 것도 뭐가 이리 복잡한지.. 기초가 없으니 매번 이 모양이다. ^^;

Post navigation

Previous Post:

문서편집기 에디트플러스(EditPlus) 버전 3.31 패치 빌드1279

Next Post:

PHP로 달력 만들기 v2

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

  • SK 세븐모바일 유심 셀프교체
  • php 배열 연산에서 + 와 array_merge 의 차이
  • pcntl_fork 를 이용한 다중 프로세스 실행
  • 아이폰 단축어를 이용하여 주중 공휴일엔 알람 울리지 않게 하기
  • 구글 캘린더 전체일정 재동기화
  • OpenLiteSpeed 웹서버에 HTTP 인증 적용
  • OpenLiteSpeed 웹어드민 도메인 연결
  • WireGuard를 이용한 VPN 환경 구축
  • Ubuntu 22.04 서버에 OpenLiteSpeed 웹서버 세팅
  • 맥 vim 세팅

Recent Comments

  • 편리 on 업무관리용 그누보드 게시판 스킨
  • 임종섭 on 업무관리용 그누보드 게시판 스킨
  • 캐논 5D 펌웨어 | Dslr 펌웨어 업그레이드 방법 82 개의 베스트 답변 on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • Top 5 캐논 5D 펌웨어 Top 89 Best Answers on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • 편리 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 임팀장 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 편리 on Notepad++ NppFTP 플러그인 수동 설치
  • paul-j on Notepad++ NppFTP 플러그인 수동 설치
  • YS on Windows 10 iCloud 사진 저장 폴더 변경
  • 편리 on Docker를 이용한 Centos7 + httpd + php 5.4 개발환경 구축

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
© 2025 CHICPRO | Built using WordPress and SuperbThemes