【问题标题】:Angular UI Bootstrap Datepicker: How to use date as a string and in a specific formatAngular UI Bootstrap Datepicker:如何将日期用作字符串并以特定格式使用
【发布时间】:2015-09-04 14:01:55
【问题描述】:

我想要做的是当用户选择特定日期时,能够将该日期用作字符串,将其作为数据放入 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();
  }
 }
});

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

【问题讨论】:

    标签: angularjs angular-ui-bootstrap bootstrap-datepicker


    【解决方案1】:

    试试这个-

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

    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 模型。

    参考链接

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

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

    【讨论】:

    • Hellon Aparna,这是有角度的吗?
    • 其实我也遇到了同样的问题。由于我们使用的是 laravel 框架,因此输入的日期采用 laravel 格式。在上面的代码中,输入来自请求
    • 好吧,因为 -> 符号让我很困惑
    • 您使用的后端和框架是什么?
    • 我正在使用 Java Jersey
    【解决方案2】:

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

        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;
    

    【讨论】:

    • 你好 Tarun,$scope.dt 包含选定的日期
    • 这不仅仅是一天,而是一个日期。只需在我的代码中将 'date' 替换为 '$scope.dt'。
    • Tarun 我无法让它工作,我将 $scope.dt 分配给一个变量,例如 dateFormated 并将它在你的代码中替换为一个指令,但它给了我一个语法错误
    • 请创建一个插件。这种方式帮不了你。
    • 确实如此!虽然它在我的项目中工作,请给我一点时间
    猜你喜欢
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 2018-08-30
    • 2016-02-11
    • 1970-01-01
    • 2014-02-19
    相关资源
    最近更新 更多