Javascript 使用 moment Angularjs 格式化日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28507256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:54:01  来源:igfitidea点击:

Format date using moment Angularjs

javascriptangularjs

提问by user3842029

I am trying to format date using moment in Angularjs but its not working for me. Here is my fiddle http://jsfiddle.net/sed6x5e8/and below is my code.

我正在尝试在 Angularjs 中使用 moment 格式化日期,但它对我不起作用。这是我的小提琴http://jsfiddle.net/sed6x5e8/下面是我的代码。

HTML:

HTML:

<div ng-app="miniapp">
    <div ng-controller="Ctrl">
        <div>
            Actual Date: {{date}}
            <br><br>
            Formatted Date: {{formattedDate}}
        </div>

    </div>    
</div>

JS:

JS:

var $scope;
var app = angular.module('miniapp', [])
function Ctrl($scope) {
    $scope.date = '2/13/2015';
    $scope.formattedDate = moment($scope.date).format('YYYY-MM-DD');
}

采纳答案by jsonmurphy

I've used angular-momentsuccessfully in a project of mine. It has a filter that alows you to format the date. Example from the README:

我在我的一个项目中成功地使用了角力矩。它有一个过滤器,可以让您格式化日期。README 中的示例:

<span>{{message.time | amDateFormat:'dddd, MMMM Do YYYY, h:mm:ss a'}}</span>

回答by ribsies

AngularJS has a built in filter for dates. You do not need to use moment, waste of resources.

AngularJS 有一个内置的日期过滤器。你不需要使用时刻,浪费资源。

<span>{{message.time | date}}</span>

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

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

回答by Malleswar Reddy

sample example

示例

var app = angular.module("app", []);

app.constant("moment", moment);

app.controller("ctrl", function($scope, moment) {
    $scope.date = new moment().format("D/MMM/YYYY");
    var dat1 = new moment();
    $scope.date3 = dat1.add('5', 'd').format('MMMM Do YYYY, h:mm:ss a');
});

Html

html

var app = angular.module("app", []);

app.constant("moment", moment);

app.controller("ctrl", function($scope, moment) {
    $scope.date = new moment().format("D/MMM/YYYY");
    var dat1 = new moment();
    $scope.date3 = dat1.add('5', 'd').format('MMMM Do YYYY, h:mm:ss a');
});
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
    {{ date }} 
  </br>
  </br>
  {{date3}}
</div>