Search code examples
javascriptangularjstimestampangularjs-ng-repeat

How to group by a date with a timestamp? (AngularJS)


I have the following code:

<div ng-repeat="(key, value) in history | groupBy:'date'">
  <div>{{key}}</div>
  <div ng-repeat="item in value">
    {{item}}
  </div>
</div>

I want to show my history in this format:

2015-10-10
item 1
item 2
item 3

2015-10-11
item 4
item 5

2015-10-12
item 6
item 7

This code works correctly, but the date property is a timestamp. Each item differs by hours and seconds. It's important that the items are grouped by day without the time.


Solution

  • According to this answer made by the author of angular-filter I found a nice solution using momentjs:

    html

    <div ng-repeat="(key, value) in history | map: toDay | groupBy:'date'">
        <div>{{key}}</div>
        <div ng-repeat="item in value">
            {{item}}
        </div>
    </div>
    

    controller

    $scope.toDay = toDay;
    
    function toDay( history ) {
        history.day = moment( history.date ).format( "L" );
        return history;
    }
    

    Assuming you have a valid javascript Date object without using momentjs your function would be alike:

    function toDay( history ) {
        history.date = history.date.toLocaleDateString();
        return history;
    };