js 格式化日期 ("/Date(1400046388387)/")


當程序異步提交的時候,而且返回是返回json的時候,你這js中接到的時間很可能就是這個樣子:"/Date(1400046388387)/",這就是一個字符串。

當然你不能把他原樣顯示在頁面上,要對他進行格式化: 網上搜羅的方法記錄在此:

1、首先對這個返回值進行轉換,轉成js的Date類型

2、利用Date的format方法進行格式化輸出(這個format方法是自己擴展的)

 

復制代碼
var str = '/Date(1400046388387)/';
var d = eval('new ' + str.substr(1, str.length - 2)); //new Date()
d.format("yyyy-MM-dd hh:mm:ss")

Date.prototype.Format = function (fmt) { //author: meizz 
    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;
}
復制代碼

 

如果不是json返回的話,最好在后台用c# ToString("yyyy-MM-dd hh:mm:ss") 方式轉換好再傳到前台,不用js的轉換。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM