JavaScriptで日付を操作する関数を作っているのですが、これをメソッドとして追加できないか、調べてみました。
サンプルを3個、紹介しています。
いずれも「var dateObj = new Date(2012, 1, 15);」に対してメソッドを適用しています。これは「2012年2月15日」になります。閏年の2月であることに注意してください。サンプル2とサンプル3はこの行を省略しています。
サンプル1
Dateオブジェクトは1月が「0」、2月が「1」となります。日本語にはなじまない仕様です。
そのため、月を表示するには1を加える必要があります。
「getTsuki」は日本語の月を返します。
var dateObj = new Date(2012, 1, 15);
Date.prototype.getTsuki = function() {
return this.getMonth() + 1;
}
document.write(dateObj.getTsuki());
//実行結果「2」
Date.prototype.getTsuki = function() {
return this.getMonth() + 1;
}
document.write(dateObj.getTsuki());
//実行結果「2」
サンプル2
「getYobi」は日本語の曜日を返します。
Date.prototype.getYobi = function() {
var yobis = ["日", "月", "火", "水", "木", "金", "土"];
return yobis[this.getDay()];
}
document.write(dateObj.getYobi());
//実行結果「水」
var yobis = ["日", "月", "火", "水", "木", "金", "土"];
return yobis[this.getDay()];
}
document.write(dateObj.getYobi());
//実行結果「水」
サンプル3
引数を与えるケースを考えました。
「getSonohi」は日を与えると、日付が属する月の日の日付オブジェクトを返します。
「2012年2月15日」に「1日」を与えると「2012年2月1日」を返します。「30日」を与えると「2012年2月30日」などないですから、その月の末日である「2012年2月29日」を返します。
Date.prototype.getSonohi = function(hi) {
sonohi = new Date(this.getFullYear(), this.getMonth(), hi);
if (sonohi.getMonth() > this.getMonth()) {
sonohi = new Date(this.getFullYear(), this.getMonth() + 1, 0);
}
return sonohi;
}
document.write(dateObj.getSonohi(30));
//実行結果「Wed Feb 29 2012 00:00:00 GMT+0900 (東京 (標準時)) 」
sonohi = new Date(this.getFullYear(), this.getMonth(), hi);
if (sonohi.getMonth() > this.getMonth()) {
sonohi = new Date(this.getFullYear(), this.getMonth() + 1, 0);
}
return sonohi;
}
document.write(dateObj.getSonohi(30));
//実行結果「Wed Feb 29 2012 00:00:00 GMT+0900 (東京 (標準時)) 」
コメント