Home > Web Front-end > JS Tutorial > body text

JS handles json date formatting problem_javascript skills

WBOY
Release: 2016-05-16 15:37:27
Original
1233 people have browsed it

起因

对于从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 &#63; "0" + (date.getMonth() + 1) : date.getMonth() + 1;
  var currentDate = date.getDate() < 10 &#63; "0" + date.getDate() : date.getDate();

  return date.getFullYear()
    + "年"
    + month
    + "月"
    + currentDate
    + "日"
    + " "
    + date.getHours()
    + ":"
    + date.getMinutes();
}
//调用:ChangeDateFormat(data[i].arrDate)
Copy after login

调用

$.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号)
      }
    });
Copy after login

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 &#63; o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
  }
  }
 return format;
}
Copy after login

使用方法:

 var testDate = new Date();
var testStr = testDate.format("YYYY年MM月dd日hh小时mm分ss秒");
alert(testStr);
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template