#### 1.1.2 JavaScript日期函數strftime(1)
很多編程語言都提供strftime或類似的函數。它對日期或時間戳進行操作,接受一個格式字符串,然后產生一個代表該日期的格式化字符串。例如,在Ruby中,提供strftime作為對時間或日期對象的方法,在清單1.1中我們給出它的使用實例。
清單1.1 Ruby中的Time#strftime
~~~
Time.now.strftime("Printed on %m/%d/%Y")
#=>"Printed on 09/09/2010"
~~~
清單1.2中給出了在JavaScript中實現strftime的最初版本。它是在Date.prototype上實現的,因此所有的日期對象都會有這個方法。這里需要提醒的是,如果您讀不懂本章的代碼也沒關系。概念比實際的代碼要重要,我們將會在第2章中討論最先進的技巧。
清單1.2 JavaScript strftime的起點
~~~
Date.prototype.strftime =(function (){
function strftime(format){
var date =this;
return (format +"").replace(/%([a-zA-Z ])/g,
function (m,f){
var formatter =Date.formats &&Date.formats [f];
if (typeof formatter =="function"){
return formatter.call(Date.formats,date);
}else if (typeof formatter =="string"){
return date.strftime(formatter);
}
return f;
});
}
//Internal helper
function zeroPad(num){
return (+num <10 ?"0":"")+num;
}
Date.formats ={
//Formatting methods
d:function (date){
return zeroPad(date.getDate());
},
m:function (date){
return zeroPad(date.getMonth()+1);
},
y:function (date){
return date.getYear()%100;
},
Y:function (date){
return date.getFullYear();
},
//Format shorthands
F:"%Y-%m-%d",
D:"%m/%d/%y"
};
return strftime;
}());
~~~
Date.prototype.strftime函數主要有兩部分:
首先,replace函數用于把格式說明符替換成它們相應的值,緊接著,Date.formats對象則是一組幫助函數。它可以分解如下:
Date.formats是一個對象,以格式說明符為關鍵字,由方法從日期中取出相應的數據作為值。
有些格式說明符只是為了方便,作為長格式的捷徑。
String.prototype.replace和一個用于匹配格式說明符的正則表達式一起使用。
replacer函數檢查在Date.formats中是否有給定的說明符,如果有,就用它;沒有,則不改變說明符(直接返回說明符)。
您將如何測試這個方法呢?一種辦法是在網頁中包含這個腳本,然后在需要的地方使用它,并且手工校驗網站能否正確顯示日期。如果它有問題,我們可能也得不到什么線索,只能跟蹤調試。一種稍復雜一點的辦法(其實也復雜不了多少)是在網頁中加載它,然后打開控制臺,在其中使用它。如清單1.3中所示的會話。
清單1.3 在Firebug中手工檢查代碼
~~~
>>>var date =new Date(2009,11,5);
>>>date.strftime("%Y");
"2009"
>>>date.strftime("%m");
"12"
>>>date.strftime("%d");
"05"
>>>date.strftime("%y");
"9"
~~~