简体   繁体   中英

Getting AngularUI Bootstrap datepicker to recognize YYYYMMDD format?

We have legacy birth date data in the format of YYYYMMDD ( 20151022 ). Angular and the ui-bootstrap datepicker obviously don't like this format. Also, our new UI requirements are to display the format as MMM, d YYYY ( Oct, 22 2015 ). I'm not seeing a way to enforce a non-standard date format (for data, not for display) in the documentation. Is this not supported or am I just overlooking it?

I assume your datepicker is bound to a variable - ng-model="date" . Then simply $watch this variable and do the nessecary formatting when a string is assigned to it :

$scope.date = ''; 

$scope.$watch('date', function(newValue, oldValue) {
    if (typeof newValue == 'string') {
      var tempDate = new Date(
          newValue.substr(4,2)+'-'+
          newValue.substr(6,2)+'-'+
          newValue.substr(0,4)
       );
       $scope.date = !isNaN(tempDate.getTime()) ? tempDate : new Date();
    }
}) 

This will return a valid date object if you have assigned a string to date on the format yyyymmdd ; if something has gone wrong date will be set to today.

$scope.date = '20151022'; //set the datepicker to 10-22-2015
$scope.date = new Date('01-01-1900') //etc works as usual

In order to use a display format on the form Oct, 22 2015 you are almost right, it should just be lowercase y 's :

uib-datepicker-popup="MMM, d yyyy"

the above in a plnkr -> http://plnkr.co/edit/ne60bBaTuca7wajTHP9w?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM