1. 自定義或者接受後臺傳入的字符串日期
//在當前頁面內追加換行標籤和指定的HTML內容
function w( html ){
document.body.innerHTML += "<br/>" + html;
}
//下面以"上午12:00:00"結尾的日期,是在FireFox和Chrome中的顯示結果
//在IE瀏覽器中,均顯示爲"00:00:00"
//短日期格式最好是"月/日/年"格式
var time = Date.parse("2015-11-07");
var date = new Date( time );
w( date.toLocaleString() ); // 2013年7月8日 上午12:00:00
//May、18、1998的位置可以隨意調換
time = Date.parse("May 18 1998");
var date = new Date( time );
w( date.toLocaleString() ); // 1998年5月18日 上午12:00:00
//Ju被看作July(7月) Chrome不支持
time = Date.parse("18 Ju 1998");
var date = new Date( time );
w( date.toLocaleString() ); // 1998年7月18日 上午12:00:00
//年份必須大於等於70
time = Date.parse("18 June 70");
var date = new Date( time );
w( date.toLocaleString() ); // 1970年6月18日 上午12:00:00
//GMT格式
time = Date.parse("Thu, 07 Aug 2014 11:00:14 GMT");
var date = new Date( time );
w( date.toLocaleString() ); // 2014年8月7日 下午7:00:14
//UTC格式(之一) IE6 ~ IE8不支持
time = Date.parse("1997-07-16T19:20:30");
var date = new Date( time );
w( date.toLocaleString() ); // 1997年7月17日 上午3:20:30
//帶AM/PM(小時數不能大於12)
time = Date.parse("November 9 1996 3:15 PM");
var date = new Date( time );
w( date.toLocaleString() ); // 1996年11月9日 下午3:15:00
2.比如上一步獲取到的日期定義爲dd
var tmp = dd.format("yyyy-MM-dd hh:mm:ss"); //那麼tmp爲格式化之後的日期
format方法如下
/**
* 時間對象的格式化;
*/
Date.prototype.format = function(format) {
/*
* eg:format="yyyy-MM-dd hh:mm:ss";
*/
var o = {
"M+" : this.getMonth() + 1, // month
"d+" : this.getDate(), // day
"h+" : this.getHours(), // hour
"m+" : this.getMinutes(), // minute
"s+" : this.getSeconds(), // second
"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
"S" : this.getMilliseconds()
// millisecond
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "")
.substr(4 - RegExp.$1.length));
}
for ( var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
: ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
}
以上爲將自定義字符串日期轉化爲固定格式化日期字符串的js,希望能幫到各位