Reputation: 829
I would like to convert dates retrieved from JSON string and format them yyyy-MM-dd. I am using the code below to format my the dates but oddly the dates are returning "12-31-1969" when the JSON string is for example "created_at": "2016-01-26T09:52:31Z" therefore the correct string would be 01-26-2016 not 12-31-1969.
HTML:
<li class="mark">Created:</li>
<li class="mark"> {{item.created_at | jsonDate : 'MM-dd-yyyy' }}"</li>
<li class="mark">Updated:</li>
<li class="mark"> {{item.updated_at | jsonDate : 'MM-dd-yyyy'}}</li>
Filter:
defaultPage.filter('jsonDate', ['$filter', function ($filter) {
return function (input, format) {
return (input) ? $filter('date')(parseInt(input.substr(6)), format) : '';
};
}]);
Upvotes: 3
Views: 11880
Reputation: 1969
The given date string in JSON(2016-01-26T09:52:31Z) seems to be working with the date filter available with AngularJS now. However the date string with my JSON was not working and I modified it to get the required output.
Sharing modified filter code below for those who may come here checking like me:
app.filter('jsonDate', ['$filter', function ($filter) {
return function (input, format) {
return (input) ? $filter('date')(Date.parse(input), format) : '';
};
}]);
Upvotes: 0
Reputation: 1
http://www.w3schools.com/angular/ng_filter_date.asp
nothing to do by JS just do in HTML it self
like {{item.created_at | date }}
or {{ item.created_at | date : "fullDate" }}
etc.
Upvotes: 0
Reputation: 4443
The parseInt(input.substr(6))
is unnecessary. From the documentation, the date
argument to the filter function is described as:
Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.
In your case, it is in the ISO 8601 string format, so your filter line can just be:
return (input) ? $filter('date')(input, format) : '';
Here's a fiddle that shows it working: https://jsfiddle.net/ezj2kefL/1/
Upvotes: 3
Reputation: 340
with:
parseInt(input.substr(6))
you are returning 0, which is the beginning of the epoch; thus, you get 12-31-1969.
Dates are tricky with Javascript. In my laziness, I rely on the Moment.js lib.
Sotch.io - Display Time Relatively in Angular provides an excellent example of what your are attempting, I believe along the very same lines.
Upvotes: 0