我們經常在操作的時候會發現從后台傳遞到view層的json中datetime類型變成了long型,當然你也可以從后台先轉為string類型,但是如果是從和數據庫對應的object中封裝的話,就不能再去轉為string類型了,所以需要在js中進行序列化為我們常見的標准日期格式。
直接上代碼,希望可以幫助到大家(另:本人近幾天開始做一個 MVC4.0+WCF+EF+Bootstrap的架構系列博文,希望大家支持和指正):
3 <script language="javascript"> 4 //擴展Date的format方法 5 Date.prototype.format = function (format) { 6 var o = { 7 "M+": this.getMonth() + 1, 8 "d+": this.getDate(), 9 "h+": this.getHours(), 10 "m+": this.getMinutes(), 11 "s+": this.getSeconds(), 12 "q+": Math.floor((this.getMonth() + 3) / 3), 13 "S": this.getMilliseconds() 14 } 15 if (/(y+)/.test(format)) { 16 format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); 17 } 18 for (var k in o) { 19 if (new RegExp("(" + k + ")").test(format)) { 20 format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); 21 } 22 } 23 return format; 24 } 25 /** 26 *轉換日期對象為日期字符串 27 * @param date 日期對象 28 * @param isFull 是否為完整的日期數據, 29 * 為true時, 格式如"2013-12-06 01:05:04" 30 * 為false時, 格式如 "2013-12-06" 31 * @return 符合要求的日期字符串 32 */ 33 function getSmpFormatDate(date, isFull) { 34 var pattern = ""; 35 if (isFull == true || isFull == undefined) { 36 pattern = "yyyy-MM-dd hh:mm:ss"; 37 } else { 38 pattern = "yyyy-MM-dd"; 39 } 40 return getFormatDate(date, pattern); 41 } 42 /** 43 *轉換當前日期對象為日期字符串 44 * @param date 日期對象 45 * @param isFull 是否為完整的日期數據, 46 * 為true時, 格式如"2013-12-06 01:05:04" 47 * 為false時, 格式如 "2013-12-06" 48 * @return 符合要求的日期字符串 49 */ 50 function getSmpFormatNowDate(isFull) { 51 return getSmpFormatDate(new Date(), isFull); 52 } 53 /** 54 *轉換long值為日期字符串 55 * @param l long值 56 * @param isFull 是否為完整的日期數據, 57 * 為true時, 格式如"2013-12-06 01:05:04" 58 * 為false時, 格式如 "2013-12-06" 59 * @return 符合要求的日期字符串 60 */ 61 function getSmpFormatDateByLong(l, isFull) { 62 return getSmpFormatDate(new Date(l), isFull); 63 } 64 /** 65 *轉換long值為日期字符串 66 * @param l long值 67 * @param pattern 格式字符串,例如:yyyy-MM-dd hh:mm:ss 68 * @return 符合要求的日期字符串 69 */ 70 function getFormatDateByLong(l, pattern) { 71 return getFormatDate(new Date(l), pattern); 72 } 73 /** 74 *轉換日期對象為日期字符串 75 * @param l long值 76 * @param pattern 格式字符串,例如:yyyy-MM-dd hh:mm:ss 77 * @return 符合要求的日期字符串 78 */ 79 function getFormatDate(date, pattern) { 80 if (date == undefined) { 81 date = new Date(); 82 } 83 if (pattern == undefined) { 84 pattern = "yyyy-MM-dd hh:mm:ss"; 85 } 86 return date.format(pattern); 87 } 88 //alert(getSmpFormatDate(new Date(1279849429000), true)); 89 //alert(getSmpFormatDate(new Date(1279849429000),false)); 90 //alert(getSmpFormatDateByLong(1279829423000, true)); 91 alert(getSmpFormatDateByLong(1279829423000,false)); 92 //alert(getFormatDateByLong(1279829423000, "yyyy-MM")); 93 //alert(getFormatDate(new Date(1279829423000), "yy-MM")); 94 //alert(getFormatDateByLong(1279849429000, "yyyy-MM hh:mm")); 95 </script>