gpt4 book ai didi

javascript - 多次应用日期过滤器

转载 作者:行者123 更新时间:2023-11-30 17:48:04 24 4
gpt4 key购买 nike

在我的 Angular 应用程序中,我调用了一个 WCF REST 服务,它返回一个数组 ob 对象,其中一个属性是 DateTime 类型,它以这种形式在 JSON 中序列化

[{"date":"\/Date(1295164800000-0800)\/",...

为了在我的模板中很好地显示它,我创建了一个过滤器来将该 JSON 表示形式转换为 JavaScript 日期对象。

eventsApp.filter("fromMSDate", function(){
return function (jsonDate) {
var D, dtime, T, tz, off,
dobj = jsonDate.match(/(\d+)|([+-])|(\d{4})/g);
T = parseInt(dobj[0]);
tz = dobj[1];
off = dobj[2];
if (off) {
off = (parseInt(off.substring(0, 2), 10) * 3600000) +
(parseInt(off.substring(2), 10) * 60000);
if (tz == '-') off *= -1;
}
else off = 0;
return new Date(T + off).toUTCString();
}
});

我是这样用的

            <span class="span1">Date:</span>
<span>{{event.date | fromMSDate}}</span>

所有工作都按需要进行,我确实在页面中显示了一个 JS 日期对象,但我不喜欢这种格式,所以我尝试应用 'date' 过滤器,但它没有成功。

            <span class="span1">Date:</span>
<span>{{event.date | fromMSDate | date:'medium'}}</span>

date 过滤器由于某种原因被忽略,日期显示为 Fri, 15 Mar 2013 00:00:00 GMT

我在这里做错了什么?

谢谢

最佳答案

Date.prototype.toUTCString 以 Angular 的日期过滤器无法识别的格式(“Mon, 03 Jul 2006 21:44:38 GMT”)返回日期。

From date filter docs :

[Param date:] Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.

因此,要生成日期过滤器可以理解的格式,请使用 Date.prototype.toISOString 以日期过滤器兼容的格式(“2013-10-31T08:36:14.601Z”)生成日期。

app.controller('AppCtrl', function($scope){
$scope.jsonDate = "\/Date(1295164800000-0800)\/";
});

app.filter("fromMSDate", function(){
return function (jsonDate) {
var D, dtime, T, tz, off,
dobj = jsonDate.match(/(\d+)|([+-])|(\d{4})/g);
T = parseInt(dobj[0]);
tz = dobj[1];
off = dobj[2];
if (off) {
off = (parseInt(off.substring(0, 2), 10) * 3600000) +
(parseInt(off.substring(2), 10) * 60000);
if (tz == '-') off *= -1;
}
else off = 0;
return new Date(T + off).toISOString();
}
});
<div ng-controller="AppCtrl">

<div>date json: {{jsonDate}}</div> <!-- == /Date(1295164800000-0800)/ -->
<div>date fromMSDate: {{jsonDate | fromMSDate}}</div> <!-- == 2011-01-16T00:00:00.000Z -->
<div>date medium: {{jsonDate | fromMSDate | date:'medium'}}</div> <!-- == Jan 16, 2011 1:00:00 AM -->
<div>date short: {{jsonDate | fromMSDate | date:'short'}}</div> <!-- == 1/16/11 1:00 AM -->

</div>

关于javascript - 多次应用日期过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19698975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com