简体   繁体   English

如何不使用日期过滤器而是仅使用js将字符串格式化为日期形式?

[英]how to format a string to date form without using date filter, but by only using js?

I have a input tag assosiated with some date picker plugin. 我有一个与某些日期选择器插件相关联的输入标签。

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

I want date in formatted form in the second input field . 我想在第二个输入字段中以格式化的格式显示日期。 I dont want to use date filter in ui, i want to do it in only js. 我不想在ui中使用日期过滤器,我只想在js中使用它。

i see your using angularjs, (i would use filters..., but if you insist on creating your own logic) 我看到您使用angularjs,(我会使用过滤器...,但是如果您坚持要创建自己的逻辑)

in your controller add a watcher and a formatted variable 在您的控制器中添加观察者和格式化的变量

$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)

And in your utils.js or where ever: 在您的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;
};

and you can display formattedDate to the user 您可以向用户显示formattedDate

You can consider using a filter in the controller, not in the template: 您可以考虑在控制器中而不是模板中使用过滤器:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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