0

I am getting following string from REST api, 20160220 I want to make it 20/02/2016

I am using angularJS. So I will require a filter. I have tried following

app.filter('myDateFilter', function() {

  return function(input) {

  var st = input;  
  var pattern = /(\d{4})(\d{2})(\d{2})/;
  var date = new Date(st.replace(pattern, '$1-$2-$3'));

  return date;

  }

});

And in html I have used

                <td>
                    {{t["due-date"] | myDateFilter}}
                </td>

This returns 2016-02-20T00:00:00.000Z

Regular expression issue? Can you kindly give me proper code which should have been used instead to generate 20/02/2016.

Nurul Alam
  • 332
  • 3
  • 17

2 Answers2

1

Naively converting a Date into a string results in the output you are seeing:

console.log(new Date()) // "2016-09-02T15:19:07.921Z"

Instead, make sure you format the date into a string manually before returning it. E.g. toLocaleDateString() converts the Date into a string, taking into account the browser's locale:

console.log(new Date().toLocaleDateString()) // "09/02/2016"
TimoStaudinger
  • 34,772
  • 13
  • 76
  • 86
0

What you are doing is converting a String to a Date() object, which seems right to me. If you try to show your Date() object in your view, what you get is the default date format.

In order to customize the format in which your Date() object is showing, you need to chain another filter to your custom filter. In this case you need to use date filter: https://docs.angularjs.org/api/ng/filter/date

You would only need to add it to your template, like this:

<td>
    {{t["due-date"] | myDateFilter | date : 'dd/MM/yyyy'}}
</td>

This way date filter will take as input the Date() object returned by your custom myDateFilter filter and produce a String representing that object as output.

This is a nice example of how angular filters and filter chaining are supposed to be used.

Alvaro Vazquez
  • 372
  • 3
  • 9