AngularJS 日期过滤器用法实例

2021年3月17日18:48:34 发表评论 990 次浏览

AngularJS日期过滤器用于将日期转换为指定的格式。如果未指定日期格式, 则默认日期格式为" MMM d, yyyy"。

语法如下:

{{ date | date : format : timezone }}

参数值:日期过滤器包含可选的格式和时区参数。

格式中使用的一些常见值如下:

  • " YYYY"-定义年份ex。 2019年
  • " YY"-定义年份ex。 19
  • " Y"-定义年份ex。 2019年
  • " MMMM" –定义月份的月份。四月
  • " MMM" –定义月份前。四月
  • ‘MM’–定义月份前04
  • ‘dd’–定义日期ex。 09
  • " d"-定义除息日。 9
  • ‘hh’–定义上午/下午的小时数
  • " h" –以AM / PM定义小时
  • 毫米-定义分钟
  • " m" –定义分钟
  • " ss" –定义第二
  • " s" –定义第二

格式的一些预定义值如下:

  • "短" –相当于" M / d / yy h:mm a"
  • "中" –等同于" MMM d, y h:mm:ss a"
  • " shortDate" –等同于" M / d / yy"(5/7/19)
  • " mediumDate" –等同于" MMM d, y"(2019年5月7日)
  • " longDate" –等同于" MMMM d, y"(2019年5月7日)
  • " fullDate" –等效于" EEEE, MMMM d, y"(2019年5月7日, 星期二)
  • " shortTime" –相当于" h:mm a"(上午2:35)
  • " mediumTime" –等同于" h:mm:ss a"(上午2:35:05)

范例1:本示例以给定格式显示日期。

<!DOCTYPE html>
< html >
     < head >
         < title >Date Filter</ title >
          
         < script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" >
         </ script >
     </ head >
      
     < body >
   
         < div ng-app = "gfgApp" ng-controller = "dateCntrl" >
             < p >{{ today | date : "dd.MM.y" }}</ p >
         </ div >
   
         < script >
             var app = angular.module('gfgApp', []);
             app.controller('dateCntrl', function($scope) {
                 $scope.today = new Date();
             });
         </ script >
     </ body >
</ html >

输出如下:

07.05.2019

范例2:本示例以指定的格式显示时间。

<!DOCTYPE html>
< html >
     < head >
         < title >Date Filter</ title >
          
         < script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" >
         </ script >
     </ head >
      
     < body >
   
         < div ng-app = "gfgApp" ng-controller = "dateCntrl" >
             < p >{{ today| date : 'mediumTime'}}</ p >
         </ div >
   
         < script >
             var app = angular.module('gfgApp', []);
             app.controller('dateCntrl', function($scope) {
                 $scope.today = new Date();
             });
         </ script >
     </ body >
</ html >

输出如下:

2:37:23 AM

范例3:本示例以指定格式显示日期。

<!DOCTYPE html>
< html >
     < head >
         < title >Date Filter</ title >
          
         < script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" >
         </ script >
     </ head >
      
     < body >
   
         < div ng-app = "gfgApp" ng-controller = "dateCntrl" >
             < p >{{ today| date }}</ p >
         </ div >
   
         < script >
             var app = angular.module('gfgApp', []);
             app.controller('dateCntrl', function($scope) {
                 $scope.today = new Date();
             });
         </ script >
     </ body >
</ html >

输出如下:

May 7, 2019

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: