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.

5
  • Regular expression issue Nah. It's because, you're passing the string to Date(), time is automatically added. Commented Sep 2, 2016 at 15:17
  • Sorry, I didn't get the issue: the date you are getting is correct. Commented Sep 2, 2016 at 15:18
  • @pietro909 just edited to add what exactly i am trying to do. Commented Sep 2, 2016 at 15:19
  • @Tushar anyway to remove the time and get something like 20/02/2016 ? Commented Sep 2, 2016 at 15:20
  • Possible duplicate of How to format a JavaScript date Commented Sep 2, 2016 at 15:21

2 Answers 2

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"

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.