ProgramingTip

날짜 형식은 날짜 형식을 날짜 형식화하지 않습니다.

bestdevel 2020. 11. 26. 19:40
반응형

날짜 형식은 날짜 형식을 날짜 형식화하지 않습니다.


내 각도 응용 프로그램에서 부트 날짜 선택을 사용하고 있습니다. 그러나 바인딩 된 모델의 기본 날짜 선택기에서 날짜를 선택하면 해당 ng-model이 하나의 형식 'MM / dd / yyyy'로 업데이트됩니다. 하지만 매번 이렇게 데이트를 해요

"2009-02-03T18:30:00.000Z"

대신에

02/04/2009

동일한 plunkr 링크에 대해 plunkr를 만들었습니다.

내 Html 및 컨트롤러 코드는 다음과 달라집니다.

<!doctype html>
<html ng-app="plunker">
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>
    <script src="example.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>

<div ng-controller="DatepickerDemoCtrl">
    <pre>Selected date is: <em>{{dt | date:'MM/dd/yyyy' }}</em></pre>
    <p>above filter will just update above UI but I want to update actual ng-modle</p>


    <h4>Popup</h4>
    <div class="row">
        <div class="col-md-6">
            <p class="input-group">
              <input type="text" class="form-control"
              datepicker-popup="{{format}}" 
              ng-model="dt"
              is-open="opened" min-date="minDate"
              max-date="'2015-06-22'" 
              datepicker-options="dateOptions" 
              date-disabled="disabled(date, mode)" 
              ng-required="true" 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>
    </div>
    <!--<div class="row">
        <div class="col-md-6">
            <label>Format:</label> <select class="form-control" ng-model="format" ng-options="f for f in formats"><option></option></select>
        </div>
    </div>-->

    <hr />
    {{dt}}
</div>
  </body>
</html>

각도 컨트롤러

angular.module('plunker', ['ui.bootstrap']);
var DatepickerDemoCtrl = function ($scope) {


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

    $scope.opened = true;
  };

  $scope.dateOptions = {
    formatYear: 'yy',
    startingDay: 1
  };


  $scope.format = 'dd-MMMM-yyyy';
};

내 질문을 검토해 주셔서 미리 감사드립니다.

최신 정보

내 데이터를 게시하기 위해 아래 메소드를 호출하고 VAR은 날짜 선택기 변수를 포함하는 900 크기의 배열입니다.

public SaveCurrentData(formToSave: tsmodels.ResponseTransferCalculationModelTS) {

        var query = this.EntityQuery.from('SaveFormData').withParameters({
            $method: 'POST',
            $encoding: 'JSON',
            $data: {
                VAR: formToSave.VAR,
                X: formToSave.X,
                CurrentForm: formToSave.currentForm,
            }
        });

        var deferred = this.q.defer();

        this.manager.executeQuery(query).then((response) => {
            deferred.resolve(response);
        }, (error) => {
                deferred.reject(error);
            });

        return deferred.promise;
    }

어느 쪽이 게시 나에게 가장 효과적인 솔루션으로 보이는 것을 기여하고 싶습니다. AngularUI datepicker를 사용하고 모델의 초기 값이 형식화되지 않는다고 가정하면 프로젝트에 다음 지시문을 추가하면 문제가 해결됩니다.

angular.module('yourAppName')
.directive('datepickerPopup', function (){
    return {
        restrict: 'EAC',
        require: 'ngModel',
        link: function(scope, element, attr, controller) {
      //remove the default formatter from the input directive to prevent conflict
      controller.$formatters.shift();
  }
}
});

Github에서 AngularUI 문제 에서이 솔루션을 찾았 으므로 모든 신용은 저기 사람들에게 돌아갑니다.


같이 $ 파서 사용할 수 있습니다.

window.module.directive('myDate', function(dateFilter) {
  return {
    restrict: 'EAC',
    require: '?ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(viewValue) {
        return dateFilter(viewValue,'yyyy-MM-dd');
      });
    }
  };
});

HTML :

<p class="input-group datepicker" >
  <input
     type="text"
     class="form-control"
     name="name"
     datepicker-popup="yyyy-MM-dd"
     date-type="string"
     show-weeks="false"
     ng-model="data[$parent.editable.name]" 
     is-open="$parent.opened"
     min-date="minDate"
     close-text="Close"
     ng-required="{{editable.mandatory}}"
     show-button-bar="false"
     close-on-date-selection="false"
     my-date />
  <span class="input-group-btn">
    <button type="button" class="btn btn-default" ng-click="openDatePicker($event)">
      <i class="glyphicon glyphicon-calendar"></i>
    </button>
  </span>
</p>

나는 같은 문제에 부딪 혔고 몇 시간 동안 로깅하고 조사한 후 문제를 해결했습니다.

처음으로 값이 날짜 선택기에서 설정하기 위해 $ viewValue는 그대로 날짜를 표시합니다. 내가 한 객체 객체로 구문 분석하는 것뿐입니다.

ui-bootstrap-tpls 파일에서 해당 블록을 검색하십시오.

  ngModel.$render = function() {
    var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
    element.val(date);

    updateCalendar();
  };

다음으로 대체하십시오.

  ngModel.$render = function() {
    ngModel.$viewValue = new Date(ngModel.$viewValue);
    var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
    element.val(date);

    updateCalendar();
  };

바라건대 이것은 도움이 될 것입니다 :)


format통해 지정은 datepicker-popup그냥 날짜의 형식 . 기본 ngModel은 Date 객체입니다. 이를 기본 표준 준수로 표시합니다.

date에서 필터를 사용하여 원하는대로 표시 할 수 있습니다 . 컨트롤러에서 구문 분석해야하는 경우 컨트롤러에 삽입 $filter하고 $filter('date')(date, format). 날짜 필터 문서를 참조하십시오 .


datepicker 지시문 내에서 값을 선택한 후 포맷터를 사용할 수 있습니다. 예를 들면

angular.module('foo').directive('bar', function() {
    return {
        require: '?ngModel',
        link: function(scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$formatters.push(function(value) {
                if (value) {
                    // format and return date here
                }

                return undefined;
            });
        }
    };
});

링크 .


이미 많은 답변이 작성되었는데 여기에 내 의견이 있습니다.

Angular 1.5.6 및 ui-bootstrap 1.3.3으로 모델을 추가하면 완료됩니다.

ng-model-options="{timezone: 'UTC'}" 

참고 : T00 : 00 : 00.000Z의 추가 시간에 신경 쓰지 않고 1 일 행사에 걱정되는 경우에만 사용하십시오.

여기에 Plunkr 업데이트 :

http://plnkr.co/edit/nncmB5EHEUkZJXRwz5QI?p=preview


제안 된 모든 솔루션이 저에게 효과가 없었지만 가장 가까운 솔루션은 @Rishii였습니다.

AngularJS 1.4.4 및 UI Bootstrap 0.13.3을 사용하고 있습니다.

.directive('jsr310Compatible', ['dateFilter', 'dateParser', function(dateFilter, dateParser) {
  return {
    restrict: 'EAC',
    require: 'ngModel',
    priority: 1,
    link: function(scope, element, attrs, ngModel) {
      var dateFormat = 'yyyy-MM-dd';

      ngModel.$parsers.push(function(viewValue) {
        return dateFilter(viewValue, dateFormat);
      });

      ngModel.$validators.date = function (modelValue, viewValue) {
        var value = modelValue || viewValue;

        if (!attrs.ngRequired && !value) {
          return true;
        }

        if (angular.isNumber(value)) {
          value = new Date(value);
        }

        if (!value) {
          return true;
        }
        else if (angular.isDate(value) && !isNaN(value)) {
          return true;
        }
        else if (angular.isString(value)) {
          var date = dateParser.parse(value, dateFormat);
          return !isNaN(date);
        }
        else {
          return false;
        }
      };
    }
  };
}])

내 JSP 파일에 코드를 추가하여 아래에서 문제를 해결할 수 있습니다. 이제 모델과 UI 값이 동일합니다.

<div ng-show="false">
    {{dt = (dt | date:'dd-MMMM-yyyy') }}
</div>  

ng-model의 기본 날짜 형식을 변경하는 단계

다른 날짜 형식의 경우 여기에서 jqueryui datepicker 날짜 형식 값을 확인하십시오. 예를 들어 dd / mm / yy를 사용했습니다.

angularjs 지시문 만들기

angular.module('app', ['ui.bootstrap']).directive('dt', function () {
return {
    restrict: 'EAC',
    require: 'ngModel',
    link: function (scope, element, attr, ngModel) {
        ngModel.$parsers.push(function (viewValue) {
           return dateFilter(viewValue, 'dd/mm/yy');
        });
    }
 }
});

dateFilter 함수 쓰기

function dateFilter(val,format) {
    return $.datepicker.formatDate(format,val);
}

html 페이지에서 ng-modal 속성을 작성하십시오.

<input type="text" class="form-control" date-type="string"  uib-datepicker-popup="{{format}}" ng-model="src.pTO_DATE" is-open="popup2.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" show-button-bar="false" show-weeks="false" dt />

문제를 해결하기 위해 새로운 지시문을 정의하는 것이 좋습니다.

datepicker가 이후 날짜를 표시하기 때문에 간단한 해결 방법은 모델 변수를 null로 설정 한 다음 잠시 후 현재 날짜로 설정하는 것입니다.

$scope.dt = null;
$timeout( function(){
    $scope.dt = new Date();
},100);

datepicker 및 datepicker-popup) 지시문은 ng-model이 Date 마감합니다. 여기에 설명되어 있습니다 .

ng-model이 특정 형식의 선호되는 래퍼 지시문을 지정합니다. 다음은 예입니다 ( Plunker ) :

(function () {
    'use strict';

    angular
        .module('myExample', ['ngAnimate', 'ngSanitize', 'ui.bootstrap'])
        .controller('MyController', MyController)
        .directive('myDatepicker', myDatepickerDirective);

    MyController.$inject = ['$scope'];

    function MyController ($scope) {
      $scope.dateFormat = 'dd MMMM yyyy';
      $scope.myDate = '30 Jun 2017';
    }

    myDatepickerDirective.$inject = ['uibDateParser', '$filter'];

    function myDatepickerDirective (uibDateParser, $filter) {
        return {
            restrict: 'E',
            scope: {
                name: '@',
                dateFormat: '@',
                ngModel: '='
            },
            required: 'ngModel',
            link: function (scope) {

                var isString = angular.isString(scope.ngModel) && scope.dateFormat;

                if (isString) {
                    scope.internalModel = uibDateParser.parse(scope.ngModel, scope.dateFormat);
                } else {
                    scope.internalModel = scope.ngModel;
                }

                scope.open = function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    scope.isOpen = true;
                };

                scope.change = function () {
                    if (isString) {
                        scope.ngModel = $filter('date')(scope.internalModel, scope.dateFormat);
                    } else {
                        scope.ngModel = scope.internalModel;
                    }
                };

            },
            template: [
                '<div class="input-group">',
                    '<input type="text" readonly="true" style="background:#fff" name="{{name}}" class="form-control" uib-datepicker-popup="{{dateFormat}}" ng-model="internalModel" is-open="isOpen" ng-click="open($event)" ng-change="change()">',
                    '<span class="input-group-btn">',
                        '<button class="btn btn-default" ng-click="open($event)">&nbsp;<i class="glyphicon glyphicon-calendar"></i>&nbsp;</button>',
                    '</span>',
                '</div>'
            ].join('')
        }
    }

})();
<!DOCTYPE html>
<html>

  <head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
    <script src="example.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  </head>

  <body ng-app="myExample">
    <div ng-controller="MyController">
      <p>
        Date format: {{dateFormat}}
      </p>
      <p>
        Value: {{myDate}}
      </p>
      <p>
        <my-datepicker ng-model="myDate" date-format="{{dateFormat}}"></my-datepicker>
      </p>
    </div>
  </body>

</html>


위의 답변을 확인한 후 생각해 냈고 마크 업에 추가 속성을 추가하지 완벽하게 작동했습니다.

angular.module('app').directive('datepickerPopup', function(dateFilter) {
    return {
        restrict: 'EAC',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {
            ngModel.$parsers.push(function(viewValue) {
                return dateFilter(viewValue, 'yyyy-MM-dd');
            });
        }
    }
});

마지막으로 위의 문제를 해결했습니다. 앵귤러 스트랩은 내가 기대하는 것과 똑같은 기능을 가지고 있습니다. 적용하는 것만으로도 date-format="MM/dd/yyyy" date-type="string"주어진 형식으로 ng-model을 업데이트하는 예상 동작을 얻었습니다.

<div class="bs-example" style="padding-bottom: 24px;" append-source>
    <form name="datepickerForm" class="form-inline" role="form">
      <!-- Basic example -->
      <div class="form-group" ng-class="{'has-error': datepickerForm.date.$invalid}">
        <label class="control-label"><i class="fa fa-calendar"></i> Date <small>(as date)</small></label>
        <input type="text"  autoclose="true"  class="form-control" ng-model="selectedDate" name="date" date-format="MM/dd/yyyy" date-type="string" bs-datepicker>
      </div>
      <hr>
      {{selectedDate}}
     </form>
</div>

여기 plunk 링크 가 작동 합니다.

참고 URL : https://stackoverflow.com/questions/24198669/angular-bootstrap-datepicker-date-format-does-not-format-ng-model-value

반응형