Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Get dates with suffix rd, th and st

How to format Date in Angular Java script?

Code

<p id="summaryHeader">Calendar of {{dt}}</p>

I get the value as 2014-06-05T12:38:42.744Z

I tried this

<p id="summaryHeader">Calendar of {{dt|date:'MMMM dd'}}</p>

which gives me

Calendar of June 05

I need it as Calendar of June 05th or July 2nd and so on.. the rear rd,th,st is what I am looking for.

Anuglar Docs are good but don't specify this formatting.

like image 615
Incpetor Avatar asked Jun 05 '14 12:06

Incpetor


2 Answers

I guess this is what you are looking for - http://www.michaelbromley.co.uk/blog/13/an-ordinal-date-filter-for-angularjs A custom filter using the logic

app.filter('dateSuffix', function($filter) {
  var suffixes = ["th", "st", "nd", "rd"];
  return function(input) {
    var dtfilter = $filter('date')(input, 'MMMM dd');
    var day = parseInt(dtfilter.slice(-2));
    var relevantDigits = (day < 30) ? day % 20 : day % 30;
    var suffix = (relevantDigits <= 3) ? suffixes[relevantDigits] : suffixes[0];
    return dtfilter+suffix;
  };
});

And a Demo: http://plnkr.co/edit/HiyQ9uvxQL3FRoj7hKB8?p=preview

like image 158
guru Avatar answered Sep 24 '22 05:09

guru


I wanted to have the ordinal indicator as a superscript, so used the following:

<div>{{amount}}<sup ng-bind="amount | ordinal"></sup></div>

Using the filter:

app.filter('ordinal', function() {
return function(number){
    if (isNaN(number) || number < 1){
        return '';
    } else if (number % 100 == 11 || number % 100 == 12) {
        return 'th';
    } else {
        var lastDigit = number % 10;
        if (lastDigit === 1) {
            return 'st';
        } else if (lastDigit === 2) {
            return 'nd';
        } else if (lastDigit === 3) {
            return 'rd';
        } else if (lastDigit > 3) {
            return 'th';
        }
    }
}
});

Note that this correctly renders 11th, 12th, 111th, 1012th, and not 11st.

like image 23
Nico Westerdale Avatar answered Sep 22 '22 05:09

Nico Westerdale