在許多報表或頁面上,我們常需要以特定格式呈現當前時間。以下示範幾種常見的日期時間格式,時間皆取自系統當前時間:
//1.2013-4-9 11:21:32
//2.2013年4月9日 11點21分32秒
//3.2013年4月9日 上午11點21分32秒
//4.2013年4月9日 下午13點21分32秒
對應的 JavaScript 寫法如下:
var thedate = new Date();
alert(thedate.getFullYear() + '-' + thedate.getMonth() + '-' + thedate.getDate() + ' ' + thedate.toLocaleTimeString());
alert(thedate.toLocaleDateString() + ' ' + thedate.getHours() + '點' + thedate.getMinutes() + '分' + thedate.getSeconds() + '秒');
if (thedate.getHours() < 12) {
alert(thedate.toLocaleDateString() + ' 上午' + thedate.getHours() + '點' + thedate.getMinutes() + '分' + thedate.getSeconds() + '秒');
}
else {
alert(thedate.toLocaleDateString() + ' 下午' + thedate.getHours() + '點' + thedate.getMinutes() + '分' + thedate.getSeconds() + '秒');
}
透過 Date 物件的 getFullYear、getMonth、getDate、getHours、getMinutes、getSeconds 等方法拼接字串,就能靈活產出各種顯示格式;再搭配 toLocaleDateString 與 toLocaleTimeString,即可快速得到本地化的日期與時間表示法。此外,實務上要留意 getMonth() 回傳的是從 0 開始的月份,若要顯示實際月份記得加 1。