起因
對於從C#返回的日期字段,當進行JSON序列化後,在前台JS裡顯示的並不是真正的日期,這讓我們感覺很不爽,我們不可能為了這東西,把所有日期字段都變成string吧,所以,找了一個JS的擴展方法,來實現這個功能
實現
function ChangeDateFormat(jsondate) {
jsondate = jsondate.replace("/Date(", "").replace(")/", "");
if (jsondate.indexOf("+") > 0) {
jsondate = jsondate.substring(0, jsondate.indexOf("+"));
}
else if (jsondate.indexOf("-") > 0) {
jsondate = jsondate.substring(0, jsondate.indexOf("-"));
}
var date = new Date(parseInt(jsondate, 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear()
+ "年"
+ month
+ "月"
+ currentDate
+ "日"
+ " "
+ date.getHours()
+ ":"
+ date.getMinutes();
}
//調用:ChangeDateFormat(data[i].arrDate)
調用
$.ajax({
type: "Get",
textType: "json",
url: "/UserInfo/GetUserWithdraw",
data: { id: id },
success: function (data) {
var result = html.replace(reg, function (node, key) {
return {
'Money': data.Money,
'AddTime': ChangeDateFormat(data.AddTime),
'CashTime': data.CashTime
}[key];
});
TsingdaTips.ask({ msg: result, show_btn: false, title: "提現申請詳情" });//預計打款時間等於申請時音後的(5號或20號)
}
});
PS:返回的json時間如 /Date(1290371638000)/ 形式,怎樣處理成 yyyy-MM-dd 這類格式
去掉/Date
直接格式化1290371638000
/**
* 時間對象的格式化;
*/
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;
}
使用方法:
var testDate = new Date();
var testStr = testDate.format("YYYY年MM月dd日hh小時mm分ss秒");
alert(testStr);