6

I have data from the server to display. I receive strings such as this: 2016-05-01. I need to filter the data between two dates in that format. I have a function to parse the date as it is:

$scope.parseDate = function (date) {
  return new Date(Date.parse(date));
} 

In my html I display the date with this:

{{ parseDate(item.startDate) }}`

But in the browser, the result is: "2016-07-12T00:00:00.000Z".

  1. I need the parse the string into the same format as from the server: 2016-05-01.

  2. I need a simple filter function.

I don't want to use moment.js. My backend platform is JavaScript.

senderle
  • 145,869
  • 36
  • 209
  • 233
KK SK
  • 91
  • 1
  • 2
  • 11
  • Possible duplicate of [Javascript change date into format of (dd/mm/yyyy)](https://stackoverflow.com/questions/13459866/javascript-change-date-into-format-of-dd-mm-yyyy) – TheCog19 Sep 18 '17 at 12:48
  • if you want to show the exact from the server. then display as it is. I cannot understand what you are trying to do. – Sibiraj Sep 18 '17 at 12:49
  • what is the format do you want to outpt? – firegloves Sep 18 '17 at 12:49

5 Answers5

8

Try this in your html :

{{item.startDate | date: 'MMM dd, yyyy'}}
Chandru
  • 10,864
  • 6
  • 38
  • 53
4

You can use AngularJS filter like below-

$scope.parseDate = function (date) {
    $filter('date')(new Date(Date.parse(date)), 'yyyy-MM-dd');
} 
ManishSingh
  • 1,804
  • 1
  • 12
  • 11
1

Something like

function(date) {
   var d = new Date(Date.parse(date));
   return d.getDate() + " " + d.getMonth() + " " + d.getFullYear();
}

Obviously it depends on what date format you desire to output.

Keep in mind that a function is not the best way to format a date in angular because it will be executed continuously and that cause a bad performance problem. You should use a filter like this

app.filter('mydate', function () {
    return function (input) {
        if (input) {

        var d = new Date(input);
        return d.getDate() + " " + d.getMonth() + " " + d.getFullYear();

    }
};
});
firegloves
  • 5,581
  • 2
  • 29
  • 50
0

In your HTML file try using

{{ parseDate(item.startDate) | date:'yyyy-MM-dd'}}
  • You can also use the same filter in javascript if that's easier see: https://docs.angularjs.org/api/ng/filter/date – jgerstle Sep 18 '17 at 13:22
0

You can use inbuilt date filter which Angular provides.

Something like this;

{{ date_variable | date:'dd-mm-yyyy' }}
Burhan
  • 127
  • 3
  • 9