【问题标题】:how to format a string to date form without using date filter, but by only using js?如何在不使用日期过滤器但仅使用 js 的情况下将字符串格式化为日期形式?
【发布时间】:2016-05-26 08:16:51
【问题描述】:

我有一个与一些日期选择器插件相关的输入标签。

         <input type="text"  ng-model="date"/>//for saving to db

         <input type="text" ng-model="date">   // should be able to see date in formatted form here(coming from db)

我希望在第二个输入字段中以格式化形式显示日期。我不想在 ui 中使用日期过滤器,我只想在 js 中使用。

【问题讨论】:

  • 为什么不想使用 BUILT-IN 过滤器?无论如何,您可以创建一个自定义的
  • 在输入字段中使用插件,因此构建过滤器不起作用。
  • 你能用插件展示你拥有的完整代码吗?因为否则很难说是什么问题

标签: javascript angularjs


【解决方案1】:

我看到您使用 angularjs,(我会使用过滤器...,但如果您坚持创建自己的逻辑)

在你的控制器中添加一个观察者和一个格式化变量

$scope.formattedDate = '';
$scope.$watch('date', function(newValue, oldValue) { $scope.formattedDate = newValue.format('d/m/Y'); }) // using the format function below (assuming date is a date object)

在您的 utils.js 或任何地方:

Date.prototype.format = function(format){
    var that = this;

    var month = parseInt(that.getMonth()) + 1;

    format = format.toLowerCase();
    format = format.replace('dd',(((that.getDate().toString().length <= 1)? '0' : '') + parseInt(that.getDate()).toString()));
    format = format.replace('d',parseInt(that.getDate()));
    format = format.replace('mm',(((month.toString().length <= 1)? '0' : '') + month.toString()));
    format = format.replace('m', month);
    format = format.replace('yy',that.getFullYear());
    format = format.replace('y',that.getFullYear());
    format = format.replace('hh',(((that.getHours().toString().length <= 1)? '0' : '') + (that.getHours()).toString()));
    format = format.replace('h',parseInt(that.getHours()));
    format = format.replace('ii',(((that.getMinutes().toString().length <= 1)? '0' : '') + (that.getMinutes()).toString()));
    format = format.replace('i',parseInt(that.getMinutes()));
    format = format.replace('s',parseInt(that.getSeconds()));

    return format;
};

您可以向用户显示 formattedDate

【讨论】:

    【解决方案2】:

    您可以考虑在控制器中使用过滤器,而不是在模板中:

    app.controller('test', function myCtrl($scope, $filter){
      //other controller code..
    
      //val - value to format
      $scope.date = $filter('date')(val,'dd/mm/yyyy'); //for example
    })
    

    【讨论】:

      猜你喜欢
      • 2016-09-24
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 2011-12-29
      • 2013-09-24
      • 2011-04-12
      相关资源
      最近更新 更多