如何在不使用日期过滤器的情况下将字符串格式化为日期格式,但仅使用js?

时间:2016-05-26 08:16:52

标签: javascript angularjs

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

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

2 个答案:

答案 0 :(得分:0)

我看到你使用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

答案 1 :(得分:0)

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

app.controller('test', function myCtrl($scope, $filter){
  //other controller code..

  //val - value to format
  $scope.date = $filter('date')(val,'dd/mm/yyyy'); //for example
})