ゼロと無限の間に

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

ユーザ用ツール

サイト用ツール


javascript:date

JavaScriptのDateオブジェクトを拡張 - Date.js

JavaScriptのDateオブジェクトって意外と低機能。
今のところ使い道は無いが、ちょっと拡張してみる。

コメントと更新履歴の参照はゼロと無限の間のログ » date-jsへどうぞ。

拡張した機能

  • RFC 2822形式へ変換できる
  • ISO-8601形式へ変換できる
  • 暦的に正しい日付かチェックできる (月ごとの末日の違いなど)
  • その月の最終日を取得できる

ソースコード

/**
 *  Date.js
 *  @see http://0-oo.net/sbox/javascript/date
 *  @version 0.1.1a
 *  @copyright 2008 dgbadmin@gmail.com
 *  @license http://0-oo.net/pryn/MIT_license.txt (The MIT license)
 */
 
Date.DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
Date.MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
 
Date.padZero = function(value) { return ("0" + value).slice(-2) };
Date.prototype.getTimeString = function() {
    return [
          Date.padZero(this.getHours())
        , Date.padZero(this.getMinutes())
        , Date.padZero(this.getSeconds())
    ].join(":");
};
Date.prototype.getTimezoneOffsetString = function(colon) {
    var offset = this.getTimezoneOffset() / 60;
    return (offset > 0 ? "-" : "+") + Date.padZero(Math.abs(offset)) + (colon ? ":" : "") + "00";
};
 
/**
 *    RFC2822の日付形式にする
 */
Date.prototype.toRFC2822 = function() {    //ex. "Sat, 03 Feb 2001 04:05:06 +0900"
    return [
          Date.DAYS[this.getDay()] + ","
        , Date.padZero(this.getDate())
        , Date.MONTHS[this.getMonth()]
        , this.getFullYear()
        , this.getTimeString()
        , this.getTimezoneOffsetString()
    ].join(" ");
};
/**
 *    ISO8601の日付形式にする
 */
Date.prototype.toISO8601 = function() {    //ex. "2001-02-03T04:05:06+09:00"
    var s = [
          this.getFullYear()
        , Date.padZero(this.getMonth() + 1)
        , Date.padZero(this.getDate())
    ].join("-") + "T";
    s += this.getTimeString();
    s += this.getTimezoneOffsetString(true);
    return s;
};
/**
 *    月の最終日を取得する
 */
Date.prototype.getLastDate = function() {
    return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
}
/**
 *    正しい年月日か調べる
 *    ・月は1~12の範囲で渡す
 *    ・数字の前のゼロや小数点以下のゼロは無視される
 */
Date.isValid = function(y, m, d) {
    var date = new Date(y, m - 1, d);
    return (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d);
}
javascript/date.txt · 最終更新: 2008/05/07 23:19 by dgbadmin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki