1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2<HTML> 3 <HEAD> 4<TITLE> Format Date </TITLE> 5<META NAME="Generator" CONTENT="EditPlus"> 6<META NAME="Author" CONTENT=""> 7<META NAME="Keywords" CONTENT=""> 8<META NAME="Description" CONTENT=""> 9<mce:script type="text/javascript"><!-- 10/** 11* 时间对象的格式化; 12*/ 13Date.prototype.format = function(format) { 14/* 15* eg:format="yyyy-MM-dd hh:mm:ss"; 16*/ 17var o = { 18"M+" :this.getMonth() + 1, // month 19"d+" :this.getDate(), // day 20"h+" :this.getHours(), // hour 21"m+" :this.getMinutes(), // minute 22"s+" :this.getSeconds(), // second 23"q+" :Math.floor((this.getMonth() + 3) / 3), // quarter 24"S" :this.getMilliseconds() // millisecond 25} 26 27if (/(y+)/.test(format)) { 28format = format.replace(RegExp.$1, (this.getFullYear() + "") 29.substr(4 - RegExp.$1.length)); 30} 31 32for ( var k in o) { 33if (new RegExp("(" + k + ")").test(format)) { 34format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] 35: ("00" + o[k]).substr(("" + o[k]).length)); 36} 37} 38return format; 39} 40function testDate(){//测试 41var testDate = new Date(); 42alert(testDate.format("yyyy-MM-dd hh:mm:ss"));//yyyy 一定得是小写 43alert(testDate.format("yyyy年MM月dd日hh小时mm分ss秒")); 44alert(testDate.format("yyyy年MM月dd日")); 45alert(testDate.format("MM/dd/yyyy")); 46alert(testDate.format("yyyyMMdd")); 47alert(testDate.format("hh:mm:ss")); 48} 49// --></mce:script> 50</HEAD> 51 <BODY> 52<input type="button" onclick="testDate();" value="testDate"/><!-- 测试按钮 --> 53 </BODY> 54</HTML>
原文来自: http://lovely.javaeye.com/blog/507798 本人经过实践 , 发了个比较全的代码上来