javascript没有正确地将角度ui datepicker日期转换为UTC

mk_*_*_yo 15 javascript datepicker asp.net-web-api angularjs angular-ui

我在我的项目中使用了角度ui datepicker(asp.net web api + angularjs).一切正常,但是当我试图将日期保存到Db时,它没有正确地将它转换为UTC格式并且导致1天(实际上是几个小时,但它也影响了一天).

例如,当我在datepicker中选择01/11/2014时:

Angularjs object:
Sat Nov 01 2014 00:00:00 GMT+0200 (FLE Standard Time)

In request: 
2014-10-31T22:00:00.000Z

In asp.net api controller:
{31-Oct-14 10:00:00 PM}
Run Code Online (Sandbox Code Playgroud)

Datepicker控制器:

app.controller('DatepickerCtrl', function ($scope) {
    $scope.today = function () {
        $scope.dt = new Date();
    };
    $scope.today();
    $scope.clear = function () {
        $scope.dt = null;
    };
    $scope.open = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.opened = true;
    };
    $scope.format = 'dd/MM/yyyy';
    $scope.dateOptions = {
        'starting-day': 1
    };
});
Run Code Online (Sandbox Code Playgroud)

hnml:

<div class="form-group inputGroupContainer" ng-controller="DatepickerCtrl">
                    <label for="date">Date of Birth</label>
                    <p class="input-group">
                        <input type="text" name="date1" ui-date="{dateFormat: 'yy-mm-dd'}" ui-date-format="yy-mm-dd" placeholder="DD/MM/YYYY" class="form-control" datepicker-popup="{{format}}" ng-model="user.Personal.BirthDate" max-date="currentDate" is-open="opened" close-text="Close" />
                        <span class="input-group-btn">
                            <button type="button"   class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
                        </span>
                    </p>
                </div>
Run Code Online (Sandbox Code Playgroud)

但似乎角度datepicker突出显示正确的日期:

在此输入图像描述

我试图手动将日期转换为UTC格式,但也没有成功

   toUTCDate: function (d) {
            var date = new Date(d);
            var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());//, date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()
            return _utc;
        }
Run Code Online (Sandbox Code Playgroud)

我应该指定时区还是使用角度js过滤器?

har*_*shr 19

我有完全相同的问题,解决方案是删除日期部分的时区组件.为了以更通用的方式解决问题,我编写了一个指令

csapp.directive("csDateToIso", function () {

    var linkFunction = function (scope, element, attrs, ngModelCtrl) {

        ngModelCtrl.$parsers.push(function (datepickerValue) {
            return moment(datepickerValue).format("YYYY-MM-DD");
        });
    };

    return {
        restrict: "A",
        require: "ngModel",
        link: linkFunction
    };
});
Run Code Online (Sandbox Code Playgroud)

above指令删除时区部分,仅考虑ISO日期格式输入的日期部分.

我确实使用moment.js进行日期操作.但你可以轻松转换上面不使用moment.js

编辑

像下面一样使用它

  <input ng-model='abc' cs-date-to-iso ui-datepicker>
Run Code Online (Sandbox Code Playgroud)