1. 程式人生 > >js時間物件的格式化

js時間物件的格式化

01 /**

02 * 時間物件的格式化;

03 */

04 Date.prototype.format = function(format) {

05 /*

06 * eg:format="YYYY-MM-dd hh:mm:ss";

07 */

08 var o = {

09 "M+" :this.getMonth() + 1, // month

10 "d+" :this.getDate(), // day

11 "h+" :this.getHours(), // hour

12 "m+" :this.getMinutes(), // minute

13 "s+" :this.getSeconds(), // second

14 "q+" :Math.floor((this.getMonth() + 3) / 3), // quarter

15 "S" :this.getMilliseconds()

16 // millisecond

17 }

18

19 if (/(y+)/.test(format)) {

20 format = format.replace(RegExp.$1, (this.getFullYear() + "")

21 .substr(4 - RegExp.$1.length));

22 }

23

24 for ( var k in o) {

25 if (new RegExp("(" + k + ")").test(format)) {

26 format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]

27 : ("00" + o[k]).substr(("" + o[k]).length));

28 }

29 }

30 return format;

31 }