如何在AngularJS中格式化JSON日期 [英] How to format a JSON date in AngularJS

查看:91
本文介绍了如何在AngularJS中格式化JSON日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Web服务传回JSON字符串,由于某种原因,它返回/Date(1461106800000 + 0100)/.

I am passing a JSON string back from my Web Service and for some reason it is returning /Date(1461106800000+0100)/.

我去过要返回的日期,格式为"yyyy-MM-dd"

I went the date to be returned in the format "yyyy-MM-dd"

我一直在在线搜索,并且在我的控制器中创建了一个看起来像这样的过滤器:

I have been searching online and in my controller I have created a filter which looks like this:

app.filter("dateFilter", function () {
return function (item) {
    if (item != null) {
        return new Date(parseInt(item.substr(6)));
    }
    return "";
};
});

在我的控制器中,我这样写:

In my controller I have written this:

var bens = $filter('dateFilter')(ben.GetAllEventsByUserResult.HOLIDAY_START);

返回以下内容:

如何获取yyyy-MM-dd格式的日期?

How can I get the date in the yyyy-MM-dd format?

推荐答案

尝试类似的方法,它使用带有新解析日期的内置角度日期过滤器.

try something like this, this uses the built in angular date filter with the newly parsed date.

app.filter("dateFilter", function ($filter) {
return function (item) {
    if (item != null) {
        var parsedDate = new Date(parseInt(item.substr(6)));
        return $filter('date')(parsedDate, 'yyyy-MM-dd');
    }
    return "";
};
});

实际上,我建议您不必添加所有时间使用自定义过滤器,而可以添加HTTP拦截器,该拦截器读取响应并自动解析日期,并使用递归导航整个对象.然后,在应用程序的其余部分中,您可以随时使用内置过滤器.

I'd actually recommend, instead of having to use your custom filter all the time, you can add a HTTP interceptor, that reads your response, and automatically parses the dates, navigating the whole object using recursion. Then, throughout the rest of the application, you can use the built in filters as and when.

这篇关于如何在AngularJS中格式化JSON日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆