Format Date time in AngularJS

后端 未结 13 1742
Happy的楠姐
Happy的楠姐 2020-11-30 22:00

How do I properly display the date and time in AngularJS?

The output below shows both the input and the output, with and without the AngularJS date filter:



        
相关标签:
13条回答
  • 2020-11-30 22:34

    You can use momentjs to implement date-time filter in angularjs. For example:

    angular.module('myApp')
     .filter('formatDateTime', function ($filter) {
        return function (date, format) {
            if (date) {
                return moment(Number(date)).format(format || "DD/MM/YYYY h:mm A");
            }
            else
                return "";
        };
    });
    

    Where date is in time stamp format.

    0 讨论(0)
  • 2020-11-30 22:35

    Your code should work as you have it see this fiddle.

    You'll have to make sure your v.Dt is a proper Date object for it to work though.

    {{dt | date:'yyyy-MM-dd HH:mm:ss Z'}}
    

    or if dateFormat is defined in scope as dateFormat = 'yyyy-MM-dd HH:mm:ss Z':

    {{dt | date:dateFormat }}
    
    0 讨论(0)
  • 2020-11-30 22:38

    Simplly if you want to output like "Jan 30, 2017 4:31:20 PM" then follow to simple step

    step1- Declare following variable in js controller

    $scope.current_time = new Date();
    

    step2- display in html page like

    {{current_time | date:'medium'}}

    0 讨论(0)
  • 2020-11-30 22:40

    Add $filter dependency in controller.

    var formatted_datetime = $filter('date')(variable_Containing_time,'yyyy-MM-dd HH:mm:ss Z')
    
    0 讨论(0)
  • 2020-11-30 22:41

    I know this is an old item, but thought I'd throw in another option to consider.

    As the original string doesn't include the "T" demarker, the default implementation in Angular doesn't recognize it as a date. You can force it using new Date, but that is a bit of a pain on an array. Since you can pipe filters together, you might be able to use a filter to convert your input to a date and then apply the date: filter on the converted date. Create a new custom filter as follows:

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

    Then in your markup, you can pipe the filters together:

    {{item.myDateTimeString | asDate | date:'shortDate'}}
    
    0 讨论(0)
  • 2020-11-30 22:41

    I would suggest you to use moment.js it has got a good support for date formatting according to locales.

    create a filter that internally uses moment.js method for formatting date.

    0 讨论(0)
提交回复
热议问题