通过 Javascript 或 Jquery 在客户端格式化 JSON 日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13549922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:20:23  来源:igfitidea点击:

Format JSON Datetime on client side by Javascript or Jquery

javascriptjqueryjson

提问by Nishant Kumar

Possible Duplicate:
Convert a date to string in Javascript

可能的重复:
在 Javascript 中将日期转换为字符串

I have date in json format at client side :

我在客户端有 json 格式的日期:

/Date(1352745000000)/

The code which i have tried to parse Json date:

我试图解析 Json 日期的代码:

eval(dateTime.replace(/\/Date\((\d+)\)\//gi, "new Date()"));

and

new Date(parseInt(dateTime.substr(6)));

Out put I am getting:

输出我得到:

Tue Nov 27 2012 00:00:00 GMT+0530 (India Standard Time)

Desire Output

期望输出

 2012-11-27 11:16

I am not able to figure out how we will get this.

我无法弄清楚我们将如何获得它。

回答by Asad Saeeduddin

var date = new Date(parseInt(dateTime.substr(6)));
var formatted = date.getFullYear() + "-" + 
      ("0" + (date.getMonth() + 1)).slice(-2) + "-" + 
      ("0" + date.getDate()).slice(-2) + " " + date.getHours() + ":" + 
      date.getMinutes(); 

回答by Bruno

Best not to try save space with this one :)

最好不要尝试用这个来节省空间:)

var str, year, month, day, hour, minute, d, finalDate;

str = "/Date(1352745000000)/".replace(/\D/g, "");
d = new Date( parseInt( str ) );

year = d.getFullYear();
month = pad( d.getMonth() + 1 );
day = pad( d.getDate() );
hour = pad( d.getHours() );
minutes = pad( d.getMinutes() );

finalDate =  year + "-" + month + "-" + day + " " + hour + ":" + minutes;

function pad( num ) {
    num = "0" + num;
    return num.slice( -2 );
}

回答by Tadeck

The output you are getting is not string - you are getting string representation of Dateobject.

您获得的输出不是 string - 您正在获得Dateobject 的字符串表示形式。

You need to format it in proper way before further processing. To see how to do that, just see this answer: https://stackoverflow.com/a/8398929/548696

在进一步处理之前,您需要以正确的方式对其进行格式化。要了解如何做到这一点,请参阅以下答案:https: //stackoverflow.com/a/8398929/548696

To add time to the date, see documentation on Date JS object: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

要为日期添加时间,请参阅 Date JS 对象的文档:https: //developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date