这篇文章主要介绍了 JS 处理 json 日期格式化问题的相关资料, 需要的朋友可以参考下
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写,同时也易于机器解析和生成。它基于 JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON 采用完全独立于语言的文本格式,但是也使用了类似于 C 语言家族的习惯(包括 C, C++, C#, Java, JavaScript, Perl, Python 等)。这些特性使 JSON 成为理想的数据交换语言。
起因
对于从 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 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
- var currentDate = date.getDate() < 10 ? "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 ? 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);
来源: