c# - 将日期从 json 转换为日期时间

标签 c# json angularjs datetime

我有一个函数可以向我的 C# Controller 发送一个步骤。

$scope.saveProgress = function () {

    var step6 = {
        Id: $scope.stepId,
        ProblemId: $scope.problemId,
        WhenOptions: $scope.whenOptions,
        CounterMeasures: $scope.counterMeasures,
        CounterMeasureWhens: $scope.counterMeasureWhens,
        CompletedDate: $scope.CompletedDate
        // step 6 specific data
    };

    $http.post(ROOT + '/step/SaveA3Step6/', step6)
        .success(function (result) {
            // log to console?
        }).
        error(function (data, status, headers, config) {
            // log to console?
        });
};

一切正常,但在我的 C# Controller 中日期总是以 null 结尾。

public JsonResult SaveA3Step6(A3Step6 a3Step6)
    {
        try
        {
            a3Step6.Save();
            return Json("OK", JsonRequestBehavior.AllowGet);
        }
        catch (Exception e)
        {
            return Json("Error" + e.Message);
        }
    }

调试时我发现 $scope.CompletedDate 的格式是 "/Date(1426636800000)/"。 因为我在 C# 中的 A3Step6 对象需要一个日期时间,所以它显示为空。

在将我的 $scope.CompletedDate 发回我的 C# Controller 之前,是否有一种方法可以在我的 $scope.saveProgress 函数中将它转换为日期时间?

最佳答案

您可以重复使用 Angularjs 的日期过滤器。您必须在 Controller 的构造函数中注入(inject) $filter。

var cpltDate = $filter('date')($scope.CompletedDate, 'MM/dd/yyyy');
var step6 = {
    Id: $scope.stepId,
    ProblemId: $scope.problemId,
    WhenOptions: $scope.whenOptions,
    CounterMeasures: $scope.counterMeasures,
    CounterMeasureWhens: $scope.counterMeasureWhens,
    CompletedDate: cpltDate
};

日期过滤器的完整文档:https://docs.angularjs.org/api/ng/filter/date

关于c# - 将日期从 json 转换为日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29117920/

相关文章:

c# - Thread.Interrupt 在应用程序关闭时停止长时间 sleep - 是否有更好的方法

c# - Foreach 扩展的更优雅的 LINQ 替代方案

json - Play json 写入子类给出不明确的隐含值错误

javascript - Angularjs 没有 'Access-Control-Allow-Origin'

javascript - 如何在 Angular 构造函数之外提供服务?

google-analytics - 使用 AngularJS 跟踪 Google Analytics 页面浏览量

c# - ruby 中的 hmac-sha1 不同于 C# HMACSHA1

c# - 我可以向 C# MessageBox 添加控件吗?

java - 提供 SOAP/XML + REST/JSON 的最佳方式是什么?

jquery - 一起序列化多个表单?