Displaying time in AM/PM format with Angular grid

All we need is an easy explanation of the problem, so here it is.

How would I format an Angular grid that is receiving entities that have a date time property called startTime and endTime to show time in an AM/PM format? Right now I am using:

{ field: 'StartTime', displayName: 'Start Time', cellFilter: 'date:\'hh:mm tt\''},
{ field: 'EndTime', displayName: 'End Time', cellFilter: 'date:\'hh:mm tt\''},

and obviously the ‘tt’ is showing instead of AM or PM. Has anyone done AM/PM in an Angular ngGrid before?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

It is simple, see this:

{ field: 'createdOn', displayName: 'Created On', width: '180px', 
 cellTemplate: 
"<div class='ngCellText'>{{row.entity.createdOn | date:'MM/dd/yy h:mm:ss a'}}</div>" },

That’s it

For more detail about the date format see this

Method 2

Just had to cobble some things together. First, a filter:

app.filter('ampmtime',
    function () {
        return function (value) {
            if (!value) { return ''; }
            var hours = new Date(value).getHours();
            var minutes = new Date(value).getMinutes();
            var ampm = hours >= 12 ? 'PM' : 'AM';
            hours = hours % 12;
            hours = hours ? hours : 12; // the hour '0' should be '12'
            minutes = minutes < 10 ? '0' + minutes : minutes;
            var strTime = hours + ':' + minutes + ' ' + ampm;
            return strTime;
        }
    });

Then, the call to the function on the gridOptions:

{ field: 'StartTime', displayName: 'Start Time', cellFilter: 'ampmtime'},
{field:'EndTime', displayName: 'End Time', cellFilter: 'ampmtime'}

And you’re all set.

Method 3

Just encountered this same issue and found a simpler solution using angular’s date filter.
You just need to change tt to a, like so

{ field: 'StartTime', displayName: 'Start Time', cellFilter: 'date:\'hh:mm a\''}

see angular’s refference for the date filter –
https://docs.angularjs.org/api/ng/filter/date

Method 4

For angular over V2 use shortTime with date pipe:

{{ myDate | date : 'shortTime' }}

‘shortTime’: equivalent to ‘h:mm a’ (9:03 AM).

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply