dqkyz02602
dqkyz02602
2015-07-09 03:42

如何将Angular UI datepicker中的ISO格式值更改为yyyy-mm-dd?

已采纳

I have a problem in my code. I have a datepicker in my form and in the textbox value the date format is correct but when passing in the PHP it is in ISO format just like this:

Sat Aug 29 2015 00:00:00 GMT+0800 (Malay Peninsula Standard Time)

Here's what i have in my sample code:

 <div class="container" ng-app="dateApp">

      <div ng-controller="dateCtrl">
        <h3>TEST DATE</h3>
        <div class="form-group">
          <label>Choose date: </label>
          <p class="input-group">
            <input type="text" class="form-control" csDateToIso datepicker-popup="yyyy-MM-dd" is-open="opened" ng-model="chosenDate" />
            <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>

        <div class="well" ng-bind="chosenDate"></div>

      </div>

    </div>

JS:

var dateApp = angular.module('dateApp', ['ui.bootstrap']);

dateApp.controller('dateCtrl', function($scope) {

  $scope.today = function() {
    chosenDate = new Date();
  };

  $scope.today();

  $scope.toggleMin = function() {
    $scope.minDate = $scope.minDate ? null : new Date();
  };

    $scope.toggleMin();

  $scope.clear = function () {
    $scope.dt = null;
  };

  $scope.open = function($event) {
    $event.preventDefault();
    $event.stopPropagation();

    $scope.opened = true;
  };


});

//directive ISO from -entre- not working
dateApp.directive('csDateToIso', function () {

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

            dateCtrl.$parsers.push(function (datepickerValue) {
                return moments(datepickerValue).format('YYYY-MM-DD');
            });

        };

        return {
            restrict: 'A',
            require: 'ngModel',
            link: linkFunction
        };

    });

I want to have a format like this: yyyy-mm-dd hh:i:ss

Here's the plnkr: http://plnkr.co/edit/NNqZ8v?p=preview

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongtiao2066 dongtiao2066 6年前

    I had written custom directive which can be used with ng-model and does fixes the date value to be in ISO format and strips off its time part, to get away with problems of timezone.

    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
        };
    });
    

    use this directive with ui-datepicker to fix the issue. I am using moment.js, but you can do it without moment.js as well.

    点赞 评论 复制链接分享