jQuery JSON 日期格式 mm/dd/yyyy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4259548/
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
JSON date format mm/dd/yyyy
提问by Nick Kahn
Here is what I am getting as data:
这是我得到的数据:
jsonp1290537545248( [{"Active":true,"EndDate":"\/Date(-62135578800000-0500)\/","StartDate":"\/Date(1280635200000-0400)\/"}] );
jsonp1290537545248([{"Active":true,"EndDate":"\/Date(-62135578800000-0500)\/","StartDate":"\/Date(1280635200000-0400)\/"}];
$.getJSON(url, {},
function (data) {
alert(data[0].EndDate);
alert(Date(data[0].StartDate));
//alert(data[0].StartDate.getDate());// + "/" + (data[0].StartDate.getMonth() + 1) + "/" + data[0].StartDate.getFullYear()); // alerts: "15/10/2008"
//var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date()"));
alert('dd ' + new Date(parseInt(data.substr(6))));
});
How do I get in the MM/DD/YYYY format?
如何获得 MM/DD/YYYY 格式?
回答by Mottie
I would use a similar regex to what Zain posted, but not use eval()
like this (demo):
我会使用与 Zain 发布的内容类似的正则表达式,但不会eval()
像这样使用(演示):
var start = parseInt(data.StartDate.replace(/\/Date\((.*?)[+-]\d+\)\//i,""), 10),
date = new Date( start ),
fStart = date.getMonth()+1 + '/' + date.getDate() + '/' + date.getFullYear();
And what is that end date? It doesn't seem to be a difference and if you use that number as a new date you end up with "Sun Dec 31 0000 22:59:59 GMT-0600 (Central Standard Time)"... so I wasn't sure what to do with that value.
那个结束日期是什么?似乎没有什么区别,如果您使用该数字作为新日期,您最终会得到“Sun Dec 31 0000 22:59:59 GMT-0600(中央标准时间)”……所以我没有确定如何处理该值。
回答by PleaseStand
It's necessary to consider the timezone when determining which date it is. I assume that the first part of the date is the output from Date.getTime()
of Java or JavaScript (i.e.the number of milliseconds since January 1, 1970, 00:00:00 UTC).
在确定日期时,有必要考虑时区。我假设日期的第一部分是Date.getTime()
Java 或 JavaScript的输出(即自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数)。
For the correct output for all times on a date, it is necessary to apply the timezone offset (e.g.-0500
for Eastern Standard Time) before creating the Date object and then use the UTC methods to get parts of the date. The reason is that JavaScript does not provide a Date.setTimezoneOffset()
method to set the timezone to the correct one (it's not possible to change it from the visitor's system timezone).
对于日期上所有时间的正确输出,有必要在创建日期对象之前应用时区偏移量(例如-0500
东部标准时间),然后使用 UTC 方法获取部分日期。原因是 JavaScript 没有提供Date.setTimezoneOffset()
将时区设置为正确时区的方法(无法从访问者的系统时区更改它)。
Code example
代码示例
Here's the code I came up with. It uses a regex to extract the parts of the encoded date, applies the specified timezone offset, creates a Date object, and then builds a date from the parts (demo: http://jsfiddle.net/Wa8LY/1/).
这是我想出的代码。它使用正则表达式来提取编码日期的部分,应用指定的时区偏移量,创建一个 Date 对象,然后从这些部分构建一个日期(演示:http: //jsfiddle.net/Wa8LY/1/)。
var dateParts = data[0].StartDate.match(/\((.*)([+-])(..)(..)\)/);
var dateObj = new Date(
/* timestamp in milliseconds */ Number(dateParts[1]) +
/* sign of timezone offset */ Number(dateParts[2] + '1') *
/* hours and minutes offset */ (36e5 * dateParts[3] + 6e4 * dateParts[4])
);
var dateMMDDYYYY = [dateObj.getUTCMonth() + 1,
dateObj.getUTCDate(),
dateObj.getUTCFullYear()].join('/');
Left padding the components
左填充组件
If you need to left pad the components of the date (e.g.01/01/0001
), you could use this function to help do so:
如果您需要保留日期的组件(例如01/01/0001
),您可以使用此功能来帮助这样做:
function leftPadWithZeroes(str, len) {
return (new Array(len + 1).join('0') + str).slice(-len);
}
And change the last lines to (demo: http://jsfiddle.net/5tkpV/1/):
并将最后几行更改为(演示:http: //jsfiddle.net/5tkpV/1/):
var dateMMDDYYYY = [leftPadWithZeroes(dateObj.getUTCMonth() + 1, 2),
leftPadWithZeroes(dateObj.getUTCDate(), 2),
leftPadWithZeroes(dateObj.getUTCFullYear(), 4)].join('/');
回答by Zain Shaikh
This might help. See the demo at http://jsfiddle.net/zainshaikh/pysAR/.
这可能会有所帮助。请参阅http://jsfiddle.net/zainshaikh/pysAR/ 上的演示。
var date = eval(data[0].StartDate.replace(/\/Date\((.*?)\)\//gi, "new Date()"));
And then you can use the JavaScript Date Formatscript (1.2 KB when minified and gzipped) to display it as you want.
然后您可以使用JavaScript 日期格式脚本(缩小和压缩时为 1.2 KB)根据需要显示它。
回答by Robert Koritnik
Auto convert serialized JSON dates to actual Javascript dates
自动将序列化的 JSON 日期转换为实际的 Javascript 日期
Since you're using jQuery, you might be interested in the code I've written that auto converts serialized dates to actual Javascript dates.
由于您使用的是 jQuery,您可能对我编写的自动将序列化日期转换为实际 Javascript 日期的代码感兴趣。
Your code would still use $.parseJSON()
on the client but with the second parameter where you tell it to automatically convert dates. Existing code will still work, because extended functionality only parses dates on your demand.
您的代码仍将$.parseJSON()
在客户端上使用,但使用第二个参数告诉它自动转换日期。现有代码仍然有效,因为扩展功能仅根据您的需要解析日期。
Check blog postand find out yourself. It's reusable and will work globally so you could just forget about this manual date conversion.
检查博客文章并找出自己。它是可重复使用的,并且可以在全球范围内使用,因此您可以忘记这种手动日期转换。
回答by Amit
The following worked because my datestring was "/Date(1334514600000)\"
以下有效,因为我的日期字符串是“/Date(1334514600000)\”
'function ConvertJsonDateString(jsonDate) {
var shortDate = null;
if (jsonDate) {
var regex = /-?\d+/;
var matches = regex.exec(jsonDate);
var dt = new Date(parseInt(matches[0]));
var month = dt.getMonth() + 1;
var monthString = month > 9 ? month : '0' + month;
var day = dt.getDate();
var dayString = day > 9 ? day : '0' + day;
var year = dt.getFullYear();
shortDate = monthString + '/' + dayString + '/' + year;
}
return shortDate;
};'