Search code examples
angularjsdategraphangular-date-format

Format datetime in controller in angularjs


So i want to format date time in xAxis

$scope.today = new Date(new Date(data.getFullYear(), data.getMonth(), data.getDate(), 23, 0, 0).getTime() / 1000);
Highcharts.chart('g233', {
                chart: {
                    type: 'column',
                    zoomType: 'x'
                },
                xAxis: {
                    categories: [$scope.today], //what should i do here?
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: 'Number of people'
                    }
                }]
            });

HTML code, because i use a ng-init to show graph then no idea how to get

{{today |date:'MM/DD}}

work. Most of searching here will lead to this format.

<div class="box-body">
    <div id="g233" ng-if="finish_get_hours" ng-init="view_g233()"></div>
</div>

Solution

  • You can use $filter. Inject $filter to your controller

    app.controller("Ctrl", [ "$scope", "$filter", function ($scope, $filter,){
    
      $scope.today = new Date(new Date(data.getFullYear(), data.getMonth(), data.getDate(), 23, 0, 0).getTime() / 1000);
      Highcharts.chart('g233', {
                    chart: {
                        type: 'column',
                        zoomType: 'x'
                    },
                    xAxis: {
                        categories: [$filter('date')($scope.today, "MM/DD")], 
                    },
                    yAxis: {
                        min: 0,
                        title: {
                            text: 'Number of people'
                        }
                    }]
                });
    
    }]);
    

    To more information about $filter date: https://docs.angularjs.org/api/ng/filter/date