Angularjs: 如何更改日期格式

Angularjs: how to change the date format

我正在从数据库循环获取日期。格式类似于“2015-09-21 18:30:00”。但我想将其更改为 'dd/MM/yyyy'。 我试过这样

{{obj.added_date | date : 'dd/MM/yyyy'}}

好像

2015-09-21 18:30:00 | date : 'dd/MM/yyyy'}}

如果我使用 fulldate 显示如下:

2015-09-21 18:30:00 | date : 'fullDate'}}

shortDate 显示如下:

2015-09-21 18:30:00 | date : 'shortDate'}}

我所做的是在angular JS中绑定数据之前你可以格式化数据

//Here i am taking the DOB from session and converted the format in dd-MM-yyyy format
string DOB = ((ABC.Models.Student)Session["Student"]).DOB.ToString("dd-MM-yyyy");

 //Here i have used a hidden field where i am going to store DOB in ng-Init 
 <input type="hidden" name="DOB" id="DOB" ng_init = "DOB=' " + "Date of Birth: " + DOB + "'"  /><br />

以后可以调用你的ng-bind方法显示。

<p ng-bind="DOB"></p>

您指定的日期格式与 AngularJS 文档中提供的输入规范不匹配。以下摘自https://docs.angularjs.org/api/ng/filter/date

Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.

我建议您将日期值转换为毫秒,然后将其传递给过滤器。

您传递给查看的日期实际上是一个字符串,因此 angular 日期过滤器不会将其识别为日期对象。您需要先将其转换为日期对象。

另外要小心 firefox,如果日期分隔符是 '-' 而不是 '/',它对 new Date(); 不起作用。所以我也会在下面建议

var myApp = angular.module('myApp',[]);


 myApp.controller('MyCtrl', ['$scope','$filter', function ($scope,$filter) {
       var dateStr = '2015-09-21 18:30:00';
       $scope.dt = $filter('date')(new Date(dateStr.split('-').join('/')), "d/M/yyyy 'at' h:mm a");
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<bod ng-app="myApp">

<div ng-controller="MyCtrl">
  <div>{{dt}}</div>
</div>
  </body>

编辑:我已经创建了一个过滤器,它将用于将字符串转换为日期对象并且也将在循环中工作

var myApp = angular.module('myApp',[]);


 myApp.controller("MyCtrl", function ($scope) {
   $scope.dt = '2015-09-21 18:30:00'; 
});

myApp.filter('formatDate', function(dateFilter) {
   var formattedDate = '';
   return function(dt) {
     console.log(new Date(dt.split('-').join('/'))); 
     formattedDate = dateFilter(new Date(dt.split('-').join('/')), 'd/M/yyyy');   
     return formattedDate;
   }
     
});   
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<bod ng-app="myApp">

<div ng-controller="MyCtrl">
  <div>{{dt | formatDate: dt:'d/M/yyyy'}}</div>
</div>
  </body>

希望对您有所帮助