JavaScript에서 Date 객체를 수신하기 위해 JSON을 구문 분석하는 방법은 무엇입니까?
다음과 같은 JSON 조각이 있습니다.
\/Date(1293034567877)\/
이 .NET 코드의 결과입니다.
var obj = DateTime.Now;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.Serialize(obj).Dump();
이제 내가 직면 한 문제는 JavaScript에서 이것으로부터 Date 객체를 만드는 방법입니다. 내가 찾을 수있는 것은 놀라운 정규식 솔루션 (많은 버그가 포함되어 있음)뿐이었습니다.
이것이 JavaScrip에 모두 포함되어 있기 때문에 우아한 해결책이 없다고 믿기 어렵습니다 .JavaScript 코드로 간주되는 JSON (JavaScript Object Notation)을 읽으려는 JavaScript 코드를 의미합니다. 여기서 잘 해.
또한 작업 할 수없는 평가 솔루션 (보안 위협으로 지적되는 것 외에)도 보았습니다.
정말 우아하게 할 방법이 없나요?
실제 대답이없는 비슷한 질문 :
GWT로 ASP.NET JSON 날짜 형식을 구문 분석하는 방법
날짜에 대한 표준 JSON 표현은 없습니다. @jAndy가 제안한대로하고 a DateTime
를 전혀 직렬화하지 않아야 합니다. RFC 1123 날짜 문자열 ToString("r")
이나 Unix-epoch의 초 수 또는 JavaScript에서 Date
.
이 JSON.parse
함수는 선택적 DateTime 리바이 버 함수를받습니다. 다음과 같은 기능을 사용할 수 있습니다.
dateTimeReviver = function (key, value) {
var a;
if (typeof value === 'string') {
a = /\/Date\((\d*)\)\//.exec(value);
if (a) {
return new Date(+a[1]);
}
}
return value;
}
그런 다음 전화
JSON.parse(somejsonstring, dateTimeReviver);
그리고 당신의 날짜가 올 것입니다.
Roy Tinker의 답변은 다음과 같습니다.
var date = new Date(parseInt(jsonDate.substr(6)));
그가 말했듯이 : substr 함수는 "/ Date ("부분을 취하고 parseInt 함수는 정수를 가져와 끝에 ") /"를 무시합니다. 결과 번호는 Date 생성자에 전달됩니다.
또 다른 옵션은 JavaScript가 쉽게 읽을 수 있도록 ASP 측에서 정보의 형식을 적절하게 지정하는 것입니다. 날짜에 대해 다음을 고려하십시오.
DateTime.Now()
다음과 같은 형식을 반환해야합니다.
7/22/2008 12:11:04 PM
이것을 JavaScript Date
생성자에 다음과 같이 전달하면 :
var date = new Date('7/22/2008 12:11:04 PM');
이제 변수 date
는 다음 값을 보유합니다.
Tue Jul 22 2008 12:11:04 GMT-0700 (Pacific Daylight Time)
당연히이 DateTime
객체를 JS Date
생성자가 허용 하는 모든 종류의 문자열 / int로 형식화 할 수 있습니다 .
JSON에서 JavaScript 스타일 ISO8601 날짜를 사용하는 경우 MDN 에서 사용할 수 있습니다.
var jsonDate = (new Date()).toJSON();
var backToDate = new Date(jsonDate);
console.log(jsonDate); //2015-10-26T07:46:36.611Z
문제 :
new Date(1293034567877);
이렇게하면 "Wed Dec 22 2010 16:16:07 GMT + 0000 (GMT Standard Time)"이 반환됩니다.
아니면 json에서 번호를 가져와야합니까?
JSON 날짜를 JavaScript에서 일반 날짜 형식으로 변환 할 수 있습니다.
var date = new Date(parseInt(jsonDate.substr(6)));
I know this is a very old thread but I wish to post this to help those who bump into this like I did.
if you don't care about using a 3rd party script, you can use moment,js Then you can use .format() to format it to anything you want it to.
Dates are always a nightmare. Answering your old question, perhaps this is the most elegant way:
eval(("new " + "/Date(1455418800000)/").replace(/\//g,""))
With eval we convert our string to javascript code. Then we remove the "/", into the replace function is a regular expression. As we start with new then our sentences will excecute this:
new Date(1455418800000)
Now, one thing I started using long time ago, is long values that are represented in ticks... why? well, localization and stop thinking in how is date configured in every server or every client. In fact, I use it too in databases.
Perhaps is quite late for this answer, but can help anybody arround here.
AngularJS couldn't parse .NET JSON date /Date(xxxxxxxxxxxxx)/
string either..
I side stepped this issue by formatting the date to its ISO 8601 string representation instead of dumping the Date
object directly...
Here is a sample of ASP.NET MVC code..
return Json(new {
date : DateTime.Now.ToString("O") //ISO 8601 Angular understands this format
});
I tried RFC 1123
but it doesn't work.. Angular treats this as string instead of Date.
return Json(new {
date : DateTime.Now.ToString("R") //RFC 1123 Angular won't parse this
});
I've not used .Net for things like this. If you were able to get it to print something like the following out it should work.
Note, unless you're parsing that JSON string by some other means or only expect users to have modern browers with a built in JSON parser you need to use a JS framework or JSON2 to parse the JSON string outputted by the server into a real JSON object.
// JSON received from server is in string format
var jsonString = '{"date":1251877601000}';
//use JSON2 or some JS library to parse the string
var jsonObject = JSON.parse( jsonString );
//now you have your date!
alert( new Date(jsonObject.date) );
Modern browsers, such as Firefox 3.5 and Internet Explorer 8, include special features for parsing JSON. As native browser support is more efficient and secure than eval(), it is expected that native JSON support will be included in the next ECMAScript standard.[6]
The answer to this question is, use nuget to obtain JSON.NET then use this inside your JsonResult
method:
JsonConvert.SerializeObject(/* JSON OBJECT TO SEND TO VIEW */);
inside your view simple do this in javascript
:
JSON.parse(/* Converted JSON object */)
If it is an ajax call:
var request = $.ajax({ url: "@Url.Action("SomeAjaxAction", "SomeController")", dataType: "json"});
request.done(function (data, result) { var safe = JSON.parse(data); var date = new Date(safe.date); });
Once JSON.parse
has been called, you can put the JSON date into a new Date
instance because JsonConvert
creates a proper ISO time instance
function parseJsonDate(jsonDate) {
var fullDate = new Date(parseInt(jsonDate.substr(6)));
var twoDigitMonth = (fullDate.getMonth() + 1) + ""; if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + ""; if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitMonth + "/" + twoDigitDate + "/" + fullDate.getFullYear();
return currentDate;
};
As Callum mentioned, for me, the best way is to change the Controller method to string instead of JsonResult".
public string GetValues()
{
MyObject.DateFrom = DateTime.Now;
return JsonConvert.SerializeObject(MyObject);
}
From the ajax method you can do something like this
$.ajax({
url: "/MyController/GetValues",
type: "post",
success: function (data) {
var validData = JSON.parse(data);
//if you are using datepicker and you want set a format
$("#DateFrom").val($.datepicker.formatDate("dd/mm/yy", new Date(validData.DateFrom)));
// if you want the date as returned
$("#DateFrom").val(new Date(validData.DateFrom))
}
});
using eval function works just have to remove the forward slash at front and back.
var date1 = "/Date(25200000)/"
eval("new " + date1.substring(1, date1.length - 1));
yields Thu Jan 01 1970 00:00:00 GMT-0700 (US Mountain Standard Time)
I ran into an issue with external API providing dates in this format, some times even with UTC difference info like /Date(123232313131+1000)/
. I was able to turn it js Date
object with following code
var val = '/Date(123232311-1000)/';
var pattern = /^\/Date\([0-9]+((\+|\-)[0-9]+)?\)\/$/;
var date = null;
// Check that the value matches /Date(123232311-1000)/ format
if (pattern.test(val)) {
var number = val.replace('/Date(', '',).replace(')/', '');
if (number.indexOf('+') >= 0) {
var split = number.split('+');
number = parseInt(split[0]) + parseInt(split[1]);
} else if (number.indexOf('-') >= 0) {
var split = number.split('-');
number = parseInt(split[0]) - parseInt(split[1]);
} else {
number = parseInt(number);
date = new Date(number);
}
}
//
// formats a .net date into a javascript compatible date
//
function FormatJsonDate(jsonDt)
{
var MIN_DATE = -62135578800000; // const
var date = new Date(parseInt(jsonDt.substr(6, jsonDt.length-8)));
return date.toString() == new Date(MIN_DATE).toString() ? "" : (date.getMonth() + 1) + "\\" + date.getDate() + "\\" + date.getFullYear();
}
function parseJsonDate(jsonDate) {
var fullDate = new Date(parseInt(jsonDate.substr(6)));
var twoDigitMonth = (fullDate.getMonth() + 1) + ""; if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + ""; if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitMonth + "/" + twoDigitDate + "/" + fullDate.getFullYear();
return currentDate;
};
//Use this function
var objDate=parseJsonDate("\/Date(1443812400000)\/");
alert(objDate);
참고URL : https://stackoverflow.com/questions/4511705/how-to-parse-json-to-receive-a-date-object-in-javascript
'Programing' 카테고리의 다른 글
React에서 로컬 이미지를 어떻게 참조합니까? (0) | 2020.08.13 |
---|---|
함수가 정의 된 위치를 찾는 방법은 무엇입니까? (0) | 2020.08.13 |
Resharper Ctrl-T 매핑 손실 (0) | 2020.08.13 |
Rails 마이그레이션 : t. 대체 이름이있는 참조? (0) | 2020.08.13 |
10 진수 유형에 대한 선언 접미사 (0) | 2020.08.13 |