3

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) : '';
    };
}]);
1
  • 1
    From a quick glance, seems like an issue on this: input.substr(6) Commented Jan 26, 2016 at 15:24

4 Answers 4

3

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/

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

Comments

0

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.

Comments

0

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.

Comments

0

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) : '';
    };
}]);

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.