Javascript Date オブジェクトに YYYYMMDD フォーマットで日付を返すメソッドを追加
まず、rightStr() を定義
function rightStr( str, len ){ return str.substr( str.length - len, len ) };
Javascript Date オブジェクトに YYYYMMDD フォーマットで日付を返すメソッドを追加するには
Date.method = ( "getYYYYMMDD", function(){ return this.getYare() + rightStr( "0" + ( this.getMonth() + 1 ), 2 ) + rightStr( "0" + this.getDate(), 2 ); });
若しくは
Date.getYYYYMMDD = function(){ return this.getYare() + rightStr( "0" + ( this.getMonth() + 1 ), 2 ) + rightStr( "0" + this.getDate(), 2 ); };
だと思う。※ 要確認<2010/03/25> rightStr ではなくて正規表現で書き換えようかな。<2010/03/25> 上の二つとも駄目だった(WindowsScriptHost/HTMLapplication)。なんで?以下は大丈夫。
Date.prototype.getYYYYMMDD= function(){ return this.getYare() + rightStr( "0" + ( this.getMonth() + 1 ), 2 ) + rightStr( "0" + this.getDate(), 2 ); };
<2010/03/25> rightStr() 定義が毎度しつこいので別枠に。<2010/03/25> 正規表現版の作りかけ…ってこれじゃフォーマットが違う。
Date.prototype.getYYYYMMDD= function(){ return this.toLocaleString().replace(/年/,"/").replace(/月/,"/").replace(/日/,""); };
<2010/03/25> 日付のフォーマットを可変にした。ついでに method 名も変えた。
Date.prototype.getLocaleDateString= function(delimitter){ switch(delimitter){ case "/": case "-": return this.getFullYear() + delimitter + rightStr( "0" + ( this.getMonth() + 1 ), 2 ) + delimitter + rightStr( "0" + this.getDate(), 2 ); break; case "non": return this.getFullYear() + rightStr( "0" + ( this.getMonth() + 1 ), 2 ) + rightStr( "0" + this.getDate(), 2 ); break; default: return this.getFullYear() + "年" + rightStr( "0" + ( this.getMonth() + 1 ), 2 ) + "月" + rightStr( "0" + this.getDate(), 2 ) + "日"; break; }; };
<2010/03/25> これは便利かも
[http://0-oo.net/sbox/javascript/date: title= JavaScriptのDateオブジェクトを拡張 - Date.js [ゼロと無限の間に]]