ゼロと無限の間に

フリーでオープンソースなJavaScriptとかPHPとか。

ユーザ用ツール

サイト用ツール


javascript:google-calendar-holidays

差分

このページの2つのバージョン間の差分を表示します。

この比較画面へのリンク

両方とも前のリビジョン前のリビジョン
次のリビジョン
前のリビジョン
javascript:google-calendar-holidays [2010/05/14 06:51] – 名称変更等 dgbadminjavascript:google-calendar-holidays [2015/09/22 14:19] (現在) – [GCalHolidays] dgbadmin
行 1: 行 1:
 ====== GoogleカレンダーからJSONPで日本の祝日一覧を取得 - GCalendar Holidays ====== ====== GoogleカレンダーからJSONPで日本の祝日一覧を取得 - GCalendar Holidays ======
  
-{{javascript:adore.png|}}+コメントと更新履歴の参照は[[http://0-oo.net/log/category/google-calendar-holidays/|ゼロと無限の間のログ » GCalendar Holidays]]でどうぞ。 
 + 
 +{{:javascript:jui-cal.png|}}
  
-[[http://code.google.com/apis/calendar/|Google Calendar API]]から、日本の祝日データを取得して表示するJavaScriptです。\\+[[https://developers.google.com/google-apps/calendar/|Google Calendar API V3]]から、日本の祝日データを取得して表示するJavaScriptです。\\
 Googleカレンダーに登録されている祝日なので、ハッピーマンデーの時のように休日の制度が変わっても柔軟に対応できます。\\ Googleカレンダーに登録されている祝日なので、ハッピーマンデーの時のように休日の制度が変わっても柔軟に対応できます。\\
 ただしGoogleカレンダーに登録されている祝日が間違っている(あるいは最新でない)場合もそのまま表示されます。:-X ただしGoogleカレンダーに登録されている祝日が間違っている(あるいは最新でない)場合もそのまま表示されます。:-X
  
-コメントと更新履歴の参照は[[http://0-oo.net/log/category/google-calendar-holidays/|ゼロ無限ログ » GCalendar Holidays]]でど+[[Yahho Calendar|Yahho Calendar]]または[[http://jqueryui.com/datepicker/|jQuery UI Datepicker]]合わせて使うと便利です。 
 + 
 +===== バージョン0.6.0から変更点 ===== 
 +バージョン0.5.xまではGoogle Calendar API V2から取得していましたが、Google Calendar API V2廃止にともない、バージョン0.6.0からはGoogle Calendar API V3から取得するようにしました。ただ、Google Calendar API V3はGoogle API KEYが必須になるため、**いったんサーバサイドのPHPでGoogle Calendar API V3からデータを取得し、そこからJavaScriptでデータを取得する**形にしました。そのPHP(GCalendar-Holidays.php)もこのページで公開しています。 
 + 
 +これにともない取得するGoogleカレンダーは公式版の祝日カレンダーのみになりました。(GCalendar-Holidays.phpを変更すれば任意のカレンダーを取得できます。) 
 + 
 + 
 +===== jQuery UI Datepickerに祝日を表示する ===== 
 + 
 +バージョン0.3.0からは[[http://jqueryui.com/datepicker/|jQuery UI Datepicker]]にも対応しました。\\ 
 +バージョン0.4.0からはjQuery UI Datepickerの土曜日・日曜日に背景色を付けるよにしました 
 + 
 +使い方は、jQuery UI Datepickerを使うページでGcalendar HolidaysのJavaScriptファイルを読み込むだけです。(下記サンプル参照) 
  
 ===== サンプル ===== ===== サンプル =====
 下記のページで実際に使ってみてください。\\ 下記のページで実際に使ってみてください。\\
-[[http://0-oo.net/sam/google-calendar-holidays/|GCalendar Holidaysのサンプル]]+  * [[http://0-oo.net/sam/google-calendar-holidays/|GCalendar Holidaysのサンプル]] 
 +  * [[http://0-oo.net/sam/google-calendar-holidays/jquery-ui-datepicker.php|jQuery UI Datepickerに祝日を表示するのサンプル]] 
 +  * [[http://0-oo.net/sam/google-calendar-holidays/multi-datepickers.php|複数表示のjQuery UI Datepickerに祝日を表示するのサンプル]]
  
 ※サンプルで使っているのは最新のBeta版の場合あり ※サンプルで使っているのは最新のBeta版の場合あり
 +
  
 ===== ライセンス ===== ===== ライセンス =====
行 21: 行 40:
  
 ===== ダウンロード ===== ===== ダウンロード =====
-[[http://0-oo.googlecode.com/svn/gcalendar-holidays.js|gcalendar-holidays.js]]+[[http://g.0-oo.net/gcalendar-holidays.js|gcalendar-holidays.js]]
  
 ※ダウンロードのリンク先が最新のBeta版の場合あり ※ダウンロードのリンク先が最新のBeta版の場合あり
行 27: 行 46:
 ===== GCalendar Holidays API リファレンス ===== ===== GCalendar Holidays API リファレンス =====
 ==== GCalHolidays ==== ==== GCalHolidays ====
 +=== GCalHolidays.apiUrl ===
 +  * GCalendar-Holidays.phpのURLをセットしておく。
 +
 === GCalHolidays.get(callback, year, month) === === GCalHolidays.get(callback, year, month) ===
   * 概要   * 概要
行 42: 行 64:
   * month : [オプション] 対象とする月。指定しないと一年分のデータを取得する。   * month : [オプション] 対象とする月。指定しないと一年分のデータを取得する。
  
-=== GCalHolidays.userIds === +=== GCalHolidays.datepickerStyles === 
-  * GoogleカレンダーのIDの配列を指定するプロパティ +  * [[http://jqueryui.com/datepicker/|jQuery UI Datepicker]]と合わせて使う場合、土曜・日曜日・祝日のstyle(CSS)
-  * デフォルトはGoogleの公式の日本の祝日 +
- +
-=== GCalHolidays.maxResults === +
-  * 取得するデータ最大件数を指定するプロパティ +
-  * デフォルトは31+
  
  
 ===== さらに進んだ使い方 ===== ===== さらに進んだ使い方 =====
-GCalHolidaysプロパティを変更すれば、他の国の祝日や祝日以外のデータ(Googleカレンダーで公開されているイベントのデータ)も取得できます。 +GCalendar-Holidays.phpで指定するGoogleカレンダーIDを変更すれば、他の国の祝日や祝日以外のデータ(Googleカレンダーで公開されているイベントのデータ)も取得できます。
- +
-例:サッカーの日本代表のスケジュールを取得する場合 +
-<code javascript> +
-GCalHolidays.userIds = ["k1b51v9t41vn3k0agk648pr7p0@group.calendar.google.com"]; +
-GCalHolidays.max = 50; +
-GCalHolidays.get(callback, 2008); +
-</code>+
  
  
行 65: 行 75:
 <code javascript> <code javascript>
 /** /**
- *  GCalHolidays - Googleカレンダーから日本の祝日(または他のスケジュール)を取得+ *  GCalendar Holidays - Googleカレンダーから日本の祝日を取得
   @see       http://0-oo.net/sbox/javascript/google-calendar-holidays   @see       http://0-oo.net/sbox/javascript/google-calendar-holidays
-  @version   0.2.0 +  @version   0.6.0 
-  @copyright 2008-2009 dgbadmin@gmail.com+  @copyright 2008-2014 dgbadmin@gmail.com
   @license   http://0-oo.net/pryn/MIT_license.txt (The MIT license)   @license   http://0-oo.net/pryn/MIT_license.txt (The MIT license)
- * 
-  See also 
-  @see http://code.google.com/intl/ja/apis/calendar/data/2.0/reference.html 
-  @see http://code.google.com/intl/ja/apis/gdata/docs/json.html 
  */  */
 var GCalHolidays = { var GCalHolidays = {
-    /** GoogleカレンダーID(複数でも可) */ +    /** Google Calendarから情報を取得するAPIURL */ 
-    userIds+    apiUrl: "https://gcalendar-holidays.appspot.com/",
-        "japanese__ja@holiday.calendar.google.com"  //Google公式版 +
-        //"japanese@holiday.calendar.google.com   //Google公式(英語)版 +
-        //"outid3el0qkcrsuf89fltf7a4qbacgt9@import.calendar.google.com" //mozilla.org版 +
-    ], +
- +
-    /** 取得するイベント(スケジュール)の最大件数 */ +
-    maxResults: 31,+
  
-    // @see http://code.google.com/intl/ja/apis/calendar/data/2.0/reference.html#Visibility +    /** jQuery UI Datepicker用のstyle(Themeに合わせてお好みで上書きして使う) *
-    visibility: "public", +    datepickerStyles:
- +        sunday  "background-image: none; background-color: #f99", //日曜日 
-    // @see http://code.google.com/intl/ja/apis/calendar/data/2.0/reference.html#Projection +        saturday"background-image: none; background-color: #6cf", //土曜日 
-    projection: "full-noattendees"+        holiday "background-image: none; background-color: #f9f //祝日 
 +    }
 }; };
 /** /**
行 109: 行 109:
     this._userCallback = callback;     this._userCallback = callback;
  
-    for (var i = 0, len = this.userIds.length; i < len; i++) { +    var cache = this._caches[start + ".." + end];
-        //取得済みの場合はそれを使う +
-        var cache = this._caches[i + ":"start + ".." + end]; +
-        if (cache) { +
-            callback(cache, i); +
-            continue; +
-        }+
  
-        //URL作成 +    if (cache{    //取得済みの場合はそれを使う 
-        var url = location.protocol + "//www.google.com/calendar/feeds/"; +        callback(cache, 0); 
-        url += encodeURIComponent(this.userIds[i]+ "/"; +        return;
-        url += this.visibility + "/" + this.projection; +
-        url += "?alt=json-in-script&callback=GCalHolidays.decode"; +
-        url += "&max-results=" + this.maxResults; +
-        url += "&start-min=" + start + "&start-max=" + end; +
- +
-        //scriptタグ生成 +
-        var script = document.createElement("script"); +
-        script.type = "text/javascript"; +
-        script.src = url; +
-        script.charset = "UTF-8"; +
-        document.body.appendChild(script);+
     }     }
 +
 +    //URL作成
 +    var url = GCalHolidays.apiUrl + "?timeMin=" + start + "&timeMax=" + end;
 +
 +    //scriptタグ生成
 +    var script = document.createElement("script");
 +    script.type = "text/javascript";
 +    script.src = url;
 +    script.charset = "UTF-8";
 +    document.body.appendChild(script);
 }; };
 /** /**
   JSONPによりGoogle Calendar API経由で呼び出されるfunction   JSONPによりGoogle Calendar API経由で呼び出されるfunction
   @param  Object  gdata   カレンダーデータ   @param  Object  gdata   カレンダーデータ
 +  @param  String  start   開始日付
 +  @param  String  end     終了日付
  */  */
-GCalHolidays.decode = function(gdata) { +GCalHolidays.decode = function(gdata, start, end) { 
-    var days = GCalHolidays._entries2days(gdata.feed.entry); +    var days = GCalHolidays._entries2days(gdata.items);
-    var href = gdata.feed.link[3].href; +
- +
-    //どのカレンダーか特定する +
-    var userId = decodeURIComponent(href.split("/")[5]); +
-    var index; +
-    for (var i = 0, len = this.userIds.length; i < len; i++) { +
-        if (this.userIds[i] == userId) { +
-            index = i; +
-            break; +
-        } +
-    }+
  
     //キャッシュする     //キャッシュする
-    var range = href.match(/\d{4}-\d{2}-\d{2}/g);   //日付範囲の最初の日と最後の日 +    this._caches[start + ".."end] = days;
-    this._caches[index + ":" + range[0] + ".."range[1]] = days;+
  
     //コールバック     //コールバック
-    this._userCallback(days, index);+    this._userCallback(days, 0);    // 第2引数は過去バージョンの遺産
 }; };
 /** /**
行 164: 行 147:
  */  */
 GCalHolidays._entries2days = function(entries) { GCalHolidays._entries2days = function(entries) {
 +    var days = [];
 +    var cnt = 0;
 +
     if (!entries) {     if (!entries) {
-        return [];+        return days;
     }     }
- 
-    //日付順にソート 
-    entries.sort(function(a, b) { 
-        return (a.gd$when[0].startTime > b.gd$when[0].startTime) ? 1 : -1; 
-    }); 
  
     //シンプルな器に移す     //シンプルな器に移す
-    var days = []; 
     for (var i = 0, len = entries.length; i < len; i++) {     for (var i = 0, len = entries.length; i < len; i++) {
-        var ymd = entries[i].gd$when[0].startTime.split("T")[0].split("-"); +        var entry = entries[i]
-        var title = entries[i].title.$t; +        var ymd = entry.start.date.split("T")[0].split("-"); 
-        //年月日は使いやすいように数値にする + 
-        days[i] = { year: ymd[0] * 1, month: ymd[1] * 1, date: ymd[2] * 1, title: title };+        days[cnt= { //年月日は使いやすいように数値にする 
 +            year: ymd[0] * 1, 
 +            month: ymd[1] * 1, 
 +            date: ymd[2] * 1, 
 +            title: entry.summary 
 +        }
 +        cnt++;
     }     }
 +
     return days;     return days;
 }; };
 +
 +/**
 +  jQuery UI Datepickerのカレンダーに祝日を表示する
 +  @param  Number  year    表示する年
 +  @param  Number  month   表示する月
 +  @param  Object  inst    Datepicker
 +  @see http://jqueryui.com/demos/datepicker/
 + */
 +GCalHolidays.datepicker = function(year, month, inst) {
 +    setTimeout(function() { //処理後に対象のdivが再構築されるケースを回避
 +        for (var i = 0, len = (inst.settings.numberOfMonths || 1); i < len; i++) {
 +            GCalHolidays.get(function(holidays) {
 +                for (var j = 0, len2 = holidays.length; j < len2; j++) {
 +                    var h = holidays[j];
 +                    var s = "[data-year=" + h.year + "][data-month=" + (h.month - 1) + "] a"
 +
 +                    inst.dpDiv.find(s).each(function() {
 +                        if ($(this).text() == h.date) {
 +                            $(this).addClass("gcal-holiday").attr("title", h.title);
 +                            return false;
 +                        }
 +                    });
 +                }
 +            }, year, month);
 +            
 +            month++;
 +            
 +            if (month > 12) {
 +                year++;
 +                month = 1;
 +            }
 +        }
 +    }, 1);
 +};
 +/**
 +  jQuery UI Datepickerが有効な場合はイベントハンドラとstyleをセットする
 + */
 +if (window.$ && $.datepicker && $.datepicker.setDefaults) {
 +    $.datepicker.setDefaults({
 +        beforeShow: function(input, inst) {
 +            var date = $(input).datepicker("getDate") || new Date();
 +            GCalHolidays.datepicker(date.getFullYear(), date.getMonth() + 1, inst);
 +        },
 +        beforeShowDay: function(date) { //土日のclass属性
 +            return [true, { 0: "gcal-sunday", 6: "gcal-saturday" }[date.getDay()] || ""];
 +        },
 +        onChangeMonthYear: GCalHolidays.datepicker
 +    });
 +
 +    $(function() {  //ページ表示後に土日・祝日用のstyleをセット
 +        var styles = GCalHolidays.datepickerStyles;
 +        var css = "";
 +        css += ".gcal-sunday   .ui-state-default { " + styles.sunday + " } ";
 +        css += ".gcal-saturday .ui-state-default { " + styles.saturday + " } ";
 +        css += ".ui-widget-content .gcal-holiday { " + styles.holiday + " }";
 +        $("head").append($('<style type="text/css">' + css + "</style>"));
 +    });
 +}
 </code> </code>
  
 +==== GCalendar-Holidays.php ====
 +<code php>
 +<?php
 +/**
 +  GCalendar-Holidays.php
 +  @see       http://0-oo.net/sbox/javascript/google-calendar-holidays
 +  @version   0.1.0
 +  @copyright 2014 dgbadmin@gmail.com
 +  @license   http://0-oo.net/pryn/MIT_license.txt (The MIT license)
 + */
 +
 +// Google APIのKEY
 +$googleApiKey = 'set your google api key!';
 +
 +// GoogleカレンダーのID
 +$calendarId = 'japanese__ja@holiday.calendar.google.com';
 +
 +// 日付範囲
 +$timeMin = $_GET['timeMin'];
 +$timeMax = $_GET['timeMax'];
 +validate($timeMin);
 +validate($timeMax);
 +
 +// Google Calendar API V3のパラメータ
 +$params = array(
 + 'key' => $googleApiKey,
 + 'timeMin' => $timeMin . 'T00:00:00+0900',
 + 'timeMax' => $timeMax . 'T23:59:59+0900',
 + 'fields' => 'items(start,summary)',
 +);
 +
 +// Google Calendar API V3のURL
 +$apiUrl = 'https://www.googleapis.com/calendar/v3/calendars/';
 +$apiUrl .= rawUrlEncode($calendarId) . '/events?';
 +$apiUrl .= http_build_query($params);
 +
 +// 取得&出力
 +header('Content-Type: application/javascript; charset=utf-8');
 +echo 'GCalHolidays.decode(' . file_get_contents($apiUrl) . ', "' . $timeMin . '", "' . $timeMax . '");';
 +
 +// 不正文字列は弾く
 +function validate($date) {
 + if (!preg_match('/^[-0-9]+\z/', $date)) {
 + throw new Exception($date);
 + }
 +}
 +</code>
javascript/google-calendar-holidays.1273787515.txt.gz · 最終更新: 2010/05/14 06:51 by dgbadmin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki