json 개체에서 Angular.js 형식 날짜
내 json 응답은 다음과 같습니다.
[{"Id":"dab4580b-e24d-49f8-9fd5-2e968b10d3b5","Title":"MVVM-Sidekick 入精","CreatedOn":"\/Date(1390272893353)\/","IsChecked":false},{"Id":"66a0f134-e240-4cc4-96fa-ac3807853ca7","Title":"Windows Phone 开发入精","CreatedOn":"\/Date(1390018447080)\/","IsChecked":false}]
"CreatedOn" 날짜의 형식은 '/Date(1390272893353)/'입니다.
이 결과를 html 테이블에 바인딩하면 날짜 형식을 지정할 수 없습니다.
<td>{{item.CreatedOn | date: 'yyyy-MM-dd HH:mm'}}</td>
여전히 내게 주는 것은:
/일자(1390272893353)/
서버 쪽의 코드를 변경하고 싶지 않습니다(json 문자열을 수정하지 않음). 이 날짜를 포맷하는 가장 좋은 방법은 무엇입니까?
저는 실제로 @Charminbear와 @Nikos의 답변을 조합했습니다. 이 필터는 꽤 잘 작동하고 정규 용어 없이도 꽤 명확합니다.
myApp.filter("jsDate", function () {
return function (x) {
return new Date(parseInt(x.substr(6)));
};
});
이것은 글을 쓰는 것을 가능하게 합니다.
{{ $scope.item.CreatedOn | jsDate | date:"yyyy-MM-dd" }}
한 가지 방법은 다른 필터를 작성해서 체인에 넣는 것입니다.예:
app.filter("mydate", function() {
var re = /\/Date\(([0-9]*)\)\//;
return function(x) {
var m = x.match(re);
if( m ) return new Date(parseInt(m[1]));
else return null;
};
});
기본적으로 정규 표현식을 사용하여 문자열을 파싱하고,Date
(표시된 형식과 다른 형식일 경우 정규식을 조정해야 합니다.)
다음과 같이 사용:
<td>{{item.CreatedOn | mydate | date: 'yyyy-MM-dd HH:mm'}}</td>
파티에 늦었다는 거 알아요.하지만 저는 제가 도움이 된 것이 무엇이었는지 말씀드리고 싶습니다.
<td>{{item.yourdatefield.slice(6,-2) | date:'dd-MMM-yyyy' }}</td>
나같은 게으른 코더들에게 도움이 되었으면 좋겠습니다. :)
Angular Date-Filter는 JS-Date를 예상합니다.따라서 JSON Date를 필터에 전달하기 전에 파싱해야 합니다.
시도해 보기:
<td>{{item.CreatedOnParsed | date: 'yyyy-MM-dd HH:mm'}}</td>
응답 콜백 방식으로 다음과 같은 작업을 수행합니다.
$scope.item.CreatedOnParsed = new Date(parseInt(item.CreatedOn.substr(6)));
이 답변에 나와 있는 바와 같이
EDIT 방금 게시물의 댓글에서 알 수 있듯이 날짜 필터에는 타임스탬프만으로도 충분하므로 이 정도면 충분합니다.
$scope.item.CreatedOnParsed = item.CreatedOn.substr(6);
//input - "DocDate":"\/Date(1127318400000-0000)\/"
-------
<tr dir-paginate="user in SalesOrder>
<td>{{user.DocDate | jsonDate}}</td>
</tr>
controller
----------
app.filter('jsonDate', ['$filter', function ($filter) {
return function (input, format) {
return (input)
? $filter('date')(parseInt(input.substr(6)), format)
: '';
};
}]);
JSON을 받을 때 날짜를 파싱하는 것이 더 좋을 수도 있습니다.
나는 다음 기능을 사용합니다.
(function() {
if (JSON && !JSON.parseWithDate) {
JSON.parseWithoutDate = JSON.parse; //Store the original JSON.parse function
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
JSON.parseWithDate = function (json) {
/// <summary>
/// parses a JSON string and turns ISO or MSAJAX date strings
/// into native JS date objects
/// </summary>
/// <param name="json" type="var">json with dates to parse</param>
/// </param>
/// <returns type="value, array or object" />
try {
var res = JSON.parseWithoutDate(json,
function (key, value) {
if (typeof value === 'string') {
var a = reISO.exec(value);
if (a)
return new Date(Date.UTC(+a[1], +a[2] - 1,
+a[3], +a[4], +a[5], +a[6]));
a = reMsAjax.exec(value);
if (a) {
var b = a[1].split(/[-+,.]/);
return new Date(b[0] ? +b[0] : 0 - +b[1]);
}
}
return value;
});
return res;
} catch (e) {
// orignal error thrown has no error message so rethrow with message
throw new Error("JSON content could not be parsed");
return null;
}
};
JSON.dateStringToDate = function (dtString) {
/// <summary>
/// Converts a JSON ISO or MSAJAX string into a date object
/// </summary>
/// <param name="" type="var">Date String</param>
/// <returns type="date or null if invalid" />
var a = reISO.exec(dtString);
if (a)
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3],
+a[4], +a[5], +a[6]));
a = reMsAjax.exec(dtString);
if (a) {
var b = a[1].split(/[-,.]/);
return new Date(+b[0]);
}
return null;
};
JSON.stringifyWcf = function (json) {
/// <summary>
/// Wcf specific stringify that encodes dates in the
/// a WCF compatible format ("/Date(9991231231)/")
/// Note: this format works ONLY with WCF.
/// ASMX can use ISO dates as of .NET 3.5 SP1
/// </summary>
/// <param name="key" type="var">property name</param>
/// <param name="value" type="var">value of the property</param>
return JSON.stringify(json, function (key, value) {
if (typeof value == "string") {
var a = reISO.exec(value);
if (a) {
var val = '/Date(' +
new Date(Date.UTC(+a[1], +a[2] - 1,
+a[3], +a[4],
+a[5], +a[6])).getTime() + ')/';
this[key] = val;
return val;
}
}
return value;
})
};
//Make Date parsing the default
JSON.parse = JSON.parseWithDate;
}
})();
여기서 가져온 것은 http://codepaste.net/i89xhc, 입니다. 다만 제가 표준 JSON.parse 함수를 날짜를 구문 분석하는 이 버전으로 덮어씁니다.이는 Angular가 보는 모든 JSON에서 ASMX 날짜를 자동으로 파싱한다는 것을 의미합니다.
각도 $http 변환을 사용하여 사용자 정의 변환을 작성할 수도 있습니다.참조: https://docs.angularjs.org/api/ng/service/$http
그것이 .net JSON 날짜이고 당신이 moment.js를 사용하고 있다고 가정합니다.그런 다음 여기에 정의된 기능을 필터에 활용합니다.
myApp.filter('JSONdate', [
'$filter', function ($filter) {
return function (input, appformat) {
if (input != null) {
return moment(input).format(appformat);
// use the line below if you want to leverage the standard date filter on top of this
// return $filter('date')(new Date(moment(input)), appformat);
} else {
return '';
}
};
}])
언급URL : https://stackoverflow.com/questions/22435212/angular-js-format-date-from-json-object
'source' 카테고리의 다른 글
Red Hat에 Maria DB(mysql) 설치.설치 후 서비스를 시작하려면 어떻게 해야 합니까? (0) | 2023.11.05 |
---|---|
Zlib 압축이 워드프레스 다중 사이트의 파일에 대한 경로를 망쳤습니다. (0) | 2023.11.05 |
두 날짜의 차이를 어떻게 계산할 수 있습니까? (0) | 2023.11.05 |
mysql feature- scaling (0) | 2023.11.05 |
고유성 제약 조건을 조건부로 적용할 수 있습니까? (0) | 2023.11.05 |