1. 程式人生 > >使用js處理後臺返回的Date型別的資料

使用js處理後臺返回的Date型別的資料

從後臺返回的日期型別的資料,如果直接在前端進行顯示的話,顯示的就是一個從 1970-01-01 00:00:00到現在所經過的毫秒數,而在大多數業務中都不可能顯示這個毫秒數,大多數都是顯示一個正常的日期格式,所以在這裡,我們使用js對於從後臺返回的Date型別的資料進行處理.


方法一、

common.js程式碼

//日期格式化,將毫秒轉為 XXXX-XX-XX 的格式
Date.prototype.Format = function(fmt) {
var o = {
"M+" : this.getMonth() + 1, // 月份
"d+" : this.getDate(), // 日
"h+" : this.getHours(), // 小時

"m+" : this.getMinutes(), // 分
"s+" : this.getSeconds(), // 秒
"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
"S" : this.getMilliseconds()
// 毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
.substr(4 - RegExp.$1.length));
for ( var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
: (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;

};


其他js中進行使用:




方法二、

common.js程式碼:

var Common = function () {
   
    return {
        // 初始化各個函式及物件
        init: function () {

        },
        
        strIsNotEmpty
: function(str) { if (str != null && str != undefined && str != '') { return true; } return false; }, // 時間戳轉換成指定日期格式 formatTime: function(time, format) { var t = new Date(time); var tf = function(i){return (i < 10 ? '0' : '') + i}; return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){ switch(a){ case 'yyyy': return tf(t.getFullYear()); break; case 'MM': return tf(t.getMonth() + 1); break; case 'mm': return tf(t.getMinutes()); break; case 'dd': return tf(t.getDate()); break; case 'HH': return tf(t.getHours()); break; case 'ss': return tf(t.getSeconds()); break; } }) } }; }(); jQuery(document).ready(function() { Common.init(); });


在其他js中使用: