Home  >  Article  >  Web Front-end  >  JS handles json date formatting problem_javascript skills

JS handles json date formatting problem_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:37:271234browse

起因

对于从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)

调用

$.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 &#63; 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);
Statement:
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