1
+ angular . module ( 'app' )
2
+
3
+ . filter ( 'ordinalDate' , function ( $filter ) {
4
+
5
+ var getOrdinalSuffix = function ( number ) {
6
+ var suffixes = [ "'th'" , "'st'" , "'nd'" , "'rd'" ] ;
7
+ var relevantDigits = ( number < 30 ) ? number % 20 : number % 30 ;
8
+ return ( relevantDigits <= 3 ) ? suffixes [ relevantDigits ] : suffixes [ 0 ] ;
9
+ } ;
10
+
11
+ /**
12
+ * Look through the format string for any possible match for 'd'.
13
+ * It needs to ignore 'dd' and also occurrences of the letter d inside
14
+ * string such as "d 'day of' MM'.
15
+ * @param format
16
+ */
17
+ var getIndecesOfDayCharacter = function ( format ) {
18
+ var dayRegex = / (?: ' (?: [ ^ ' ] | ' ' ) * ' ) | (?: d + ) / g;
19
+ var matchingIndices = [ ] ;
20
+ var finishedLooking = false ;
21
+
22
+ while ( ! finishedLooking ) {
23
+ var matches = dayRegex . exec ( format ) ;
24
+ if ( matches ) {
25
+ dayRegex . lastIndex = matches . index + matches [ 0 ] . length ;
26
+ if ( matches [ 0 ] === 'd' ) {
27
+ matchingIndices . push ( matches . index + 1 ) ;
28
+ }
29
+ } else {
30
+ finishedLooking = true ;
31
+ }
32
+ }
33
+
34
+ return matchingIndices ;
35
+ } ;
36
+
37
+ /**
38
+ * Insert a string at a given index of another string
39
+ * @param inputString
40
+ * @param index
41
+ * @param stringToInsert
42
+ * @returns {string }
43
+ */
44
+ var insertAtIndex = function ( inputString , index , stringToInsert ) {
45
+ var partBeforeIndex = inputString . substring ( 0 , index ) ;
46
+ var partAfterIndex = inputString . substring ( index , inputString . length ) ;
47
+ return partBeforeIndex + stringToInsert + partAfterIndex ;
48
+ } ;
49
+
50
+ return function ( timestamp , format ) {
51
+ var date = new Date ( timestamp ) ;
52
+ var dayOfMonth = date . getDate ( ) ;
53
+ var suffix = getOrdinalSuffix ( dayOfMonth ) ;
54
+
55
+ var matchingIndices = getIndecesOfDayCharacter ( format ) ;
56
+
57
+ // now we to insert the suffix at the index(-ces) that we found
58
+ for ( var i = matchingIndices . length ; i > 0 ; i -- ) {
59
+ format = insertAtIndex ( format , matchingIndices [ i - 1 ] , suffix ) ;
60
+ }
61
+ return $filter ( 'date' ) ( new Date ( timestamp ) , format ) ;
62
+ } ;
63
+ } ) ;
0 commit comments