Angular UI Bootstrap Datepicker:如何将日期用作字符串和特定格式

Angular UI Bootstrap Datepicker: How to use date as a string and in a specific format

我想做的是当用户选择特定日期时,能够将该日期用作字符串,将其作为数据放入 JSON 对象并从数据库中检索数据作为回应。

选择我想要的日期我在控制台日志中得到这个:

Fri Sep 04 2015 16:15:24 GMT+0300 (GTB Daylight Time)

为了使用它,我想将它转换成这样:

20150904

我什至使用了一个指令,但我想这只是为了预览。

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

有人知道这将如何完成吗? 提前致谢!

您可以使用简单的 JavaScript 并在您认为合适的任何地方使用它(指令、过滤器、服务等)。假设 'date' 包含您的日期。这是代码:

    var year = date.getFullYear();
    var month = date.getMonth();
    month = month + 1;
    if(month < 10) {
        month = '0' + month;
    }
    var day = date.getDate();
    if(day < 10) {
        day = '0' + day;
    }
    date = year.toString() + month.toString() + day.toString();
    return date;

试试这个-

这是示例代码,您可以尝试使用您的代码 -

angular.module('frontendApp')
    .controller('SearchCtrl',function ($scope, $filter) {

        $scope.formattedDate = $filter('date')($scope.date_of_birth, "dd/MM/yyyy");
        console.log('Formatted Date: ' + $scope.formattedDate);

    });

将“$scope.date_of_birth”替换为您的 ng-model。

参考链接

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

https://sonnguyen.ws/angularjs-datetime-format/