【问题标题】:Formatting Date in Angular在 Angular 中格式化日期
【发布时间】:2016-03-10 16:33:55
【问题描述】:

目前,我的 Angular 代码显示日期如下:

2016 年 3 月 10 日

 <span class="num">{{appointment.calendarSlot}}</span>

我想这样显示日期:

3 月 25 日星期五

我该怎么做?

更新:约会.calendarSlot 是一个字符串,而不是 Javascript 日期

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

您可以使用以下date filter

 <span class="num">{{ appointment.calendarSlot | date:'EEEE, MMMM d' }}</span>

【讨论】:

  • 约会.calendarSlot 是一个字符串,而不是JS datetime 对象。
  • 我想你可能想问一个单独的问题,而不是在这里用不同的问题混淆问题和答案
【解决方案2】:

试试这个:

https://docs.angularjs.org/api/ng/filter/date

这条线适合你:

'fullDate': equivalent to 'EEEE, MMMM d, y' for en_US locale (e.g. Friday, September 3, 2010)

【讨论】:

    【解决方案3】:
    scope.date = new Date()  // controller
    
    
    {{date | date:'EEEE, MMMM dd'}} // view
    

    【讨论】:

    • 你不需要dd,只需要d
    • 这取决于)也许您需要 3 月 3 日而不是 3 月 3 日。我查看了 2016 年 3 月 10 日的原始格式。也可能是 2016 年 3 月 10 日。所以我决定把 dd 作为答案。
    【解决方案4】:

    你可以试试这个

    <div ng-app='app' ng-controller="ctrl">
        <span class="num" ng-bind="appointment.calendarSlot | date:'EEEE, MMMM d'"></span>
    </div>
    

    JS

    var app = angular.module('app', []);
    
    app.controller('ctrl', function($scope) {
        $scope.appointment = {};
        $scope.appointment.calendarSlot = new Date('03/10/2016');
    });
    

    在这里工作 JSFiddle http://jsfiddle.net/WfuAh/150/

    【讨论】:

    • 如果字符串的格式为 MM/dd/yy,如 OP 帖子中所述,则此方法无效。
    • 我同意这应该可行,但我想知道 OP 是否遗漏了一堆周围的代码。我怀疑,尽管我绝对没有任何理由可以怀疑,但问题中引用的 &lt;span&gt; 是在 ng-repeat 构造中。
    【解决方案5】:

    为了使其最灵活,我会在您的应用程序中添加一个自定义过滤器,将字符串转换为日期,然后您可以使用内置的 Angular 日期格式过滤器。

    .filter("asDate", function() {
        return function(input) {
            return Date.parse(input);
        }
    })
    

    然后你的标记变成:

    <span class="num">{{ appointment.calendarSlot | asDate | date:'EEEE, MMMM d' }}</span>
    

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 2018-09-07
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多