【问题标题】:Format Date in AngularJS coming from $http.get in large json data responseAngularJS中的格式日期来自大型json数据响应中的$http.get
【发布时间】:2016-11-04 21:16:54
【问题描述】:

我在 Angular 控制器中成功调用了 $http.get 并取回了一个大的 json 对象。像这样:

var self=this;
self.createNewStatusReport = function()
{
    $http.get(self.NewStatusReportUrl).then(function(response)
    {
        self.AngularModel.StatusReportJsons.push(response.data);
    });
};

返回的 json 包含许多日期。不幸的是,格式如下所示:/Date(1420099200000)/。这是响应数据的简化部分:

{
    "StatusReportID": 25, 
    "DueDate": "/Date(1468566000000)/", 
    "SubmitDate": null,
    "WorkStatement": [
    {
        "WorkStatementID": 41, 
        "Milestone": [
        {
            "MilestoneID": 501,
            "ContractorComments": null, 
            "Title": "Do some specific piece of work", 
            "StartDate": "/Date(1459494000000)/", 
            "EndDate": "/Date(1469948400000)/", 
            "IsCompleted": false, 
            ...

我对服务器端也有(一些)控制权,但不能从 DateTime 更改 StatusReportJson 中的日期类型?串起来。它是用 C# 编写的 MVC:

[HttpGet]
public JsonResult NewStatusReport(string agreementNumber)
{
    var statusReport = StatusReports.GetStatusReport(25);
    return Json(new StatusReportJson(statusReport), JsonRequestBehavior.AllowGet);
}

有没有一种简单的方法可以将这些日期字符串递归地转换为日期对象?我已经解析了响应数据;我可以插入自己的解析步骤吗?在服务器端,我可以在不修改我的 StatusReportJson 对象的数据类型的情况下将日期作为看起来更像“2016-04-01T00:00:00”或简单的“2016-04-01”的日期字符串输入吗?其他人已经在这里解决了转换问题:How do I format a Microsoft JSON date? 我需要帮助构建解决方案的位置,以便在我的情况下有效。感谢您的帮助!

【问题讨论】:

  • 简单地循环数据并在推送到数组之前转换每个实例。必须进行客户端数据转换并不少见
  • 这会产生我宁愿没有的依赖关系。如果 StatusReportJson 在服务器端发生变化,这很可能会发生,我不想更改客户端以匹配。使代码的可维护性降低。
  • 我不知道如何在服务器端进行更改。但在客户端,您可以只使用将 /Date()/ 字符串转换为数字的过滤器,然后将该数字传递给标准日期过滤器。
  • “使代码不易维护” ...没有意义。
  • 有趣的想法。您是在谈论 Angular 过滤器吗? (我对它们还不是很熟悉。)假设我可以查找如何编写一个,那么在解析 json 之前,我将如何将它放在此处工作?

标签: angularjs json


【解决方案1】:

希望这能解决您的问题:

$scope.DateIssue = function(input) {
input = '/Date(1468566000000)/';
$scope.formatedDate = input.toString().replace('/Date(', '').replace(')/', '');
$scope.formatedDate = $filter('date', $scope.formatedDate);
return $scope.formatedDate

};

【讨论】:

  • 谢谢。嗯。但我有一个对象,而不是一个字符串。有没有办法在 Angular 进行 json 反序列化之前运行一个预处理响应的函数?
  • 您可以将该对象转换为字符串并使用此函数。
【解决方案2】:

这就是我解决这个问题的方法。首先,我在服务器端使用了 JavaScript 序列化器,如下所示:

[HttpGet]
public JsonResult NewStatusReport(string agreementNumber)
{
    var statusReport = StatusReports.GetStatusReport(25);
    var statusReportJson = new StatusReportJson(statusReport);
    var json = new JavaScriptSerializer().Serialize(statusReportJson);
    return Json(json, JsonRequestBehavior.AllowGet);
}

然后,在客户端,我从这个出色的页面http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html 中提取代码并这样称呼它:

var self = this;
$http.get(self.NewStatusReportUrl).then(function(response)
{
    var jsonObject = jQuery.parseJSON(response.data, true);
    self.AngularModel.StatusReportJsons.push(jsonObject);
});

感谢 Robert Koritnik 的回答!并感谢所有提供帮助的人!

【讨论】:

    【解决方案3】:

    有点晚了,但我觉得很有帮助。 大多数建议是在本地转换它。在我的情况下,日期作为字符串返回(带有时区信息)。

    例如'2018-06-01T13:57:41.3867449Z'

    因此,我为 getJson 和 PostJson 创建了一个通用服务,并在其中使用 '$q' 处理响应。

    if (response.data) {
        // Check for datetime object & convert  
        // TODO:: *** May impact performance, so check later or use momentJS
        //console.info('Before-convertDateStringsToDates:', new Date());
        appUtils.convertDateStringsToDates(response.data);
        //console.info('After-convertDateStringsToDates:', new Date());
    }
    

    我的 appUtil 方法如下:

    // --------------------------------------------------------------------------------
    // Ref: http://aboutcode.net/2013/07/27/json-date-parsing-angularjs.html
    // Function to convert string (as ReGex format) property to date - used as generic in Common Serivce.
    convertDateStringsToDates(input) {
        // ReGex for format we receive from Web API e.g. "1980-05-09T00:00:00Z"
        var jsonDateTimeFormatRegex = "((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))";
        // Ignore things that aren't objects.
        if (typeof input !== "object") return input;
    
        for (var key in input) {
            if (!input.hasOwnProperty(key)) continue;
    
            var value = input[key];
            var match;
            // Check for string properties which look like dates.
            // TODO: Improve this regex to better match ISO 8601 date strings.
            if (typeof value === "string" && (match = value.match(jsonDateTimeFormatRegex))) {
                // Assume that Date.parse can parse ISO 8601 strings, or has been shimmed in older browsers to do so.
                //console.info(match[0]);
                var date = new Date(match[0]); // Need to convert to UTC. Ref: https://stackoverflow.com/a/14006555/1161069
                input[key] = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
    
                // var milliseconds = Date.parse(match[0]);
                // if (!isNaN(milliseconds)) {
                //     input[key] = new Date(milliseconds);
                // }
            } else if (typeof value === "object") {
                // Recurse into object
                this.convertDateStringsToDates(value);
            }
        }
    }
    

    现在,在每次 GET 或 POST 请求之后,我都会获得带有正确日期的 JSON。

    以防万一有人想知道 Web API 代码,如下所示:

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
    
        //var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);
    
        // Web API routes
        config.MapHttpAttributeRoutes();
    
        // other code ......
    
        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        //jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    
        JsonSerializerSettings jSettings = new JsonSerializerSettings()
        {
            Formatting = Formatting.None
        };
        jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
        jsonFormatter.SerializerSettings = jSettings;
    
        // rest of the code....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多