Issue
I have an object which I get from a server, and this object has a property: obj.year: "2017"
, for example. The property is a number
.
I need to display only the last two digits of the year.
When I format it in the HTML like this:
{{obj.year | date : 'yy'}}
it shows :70
. I tried with all kind of built Angular year filters and I tried it with a moment js
formatting function:
function formatYear(year) {
return moment(year).format('YY');
}
But it still returns the year 1970. I don't get why it returns this year, and this happens only when it's being formatted? If I don't apply any formatting on it, it returns the normal value of the object - 2017
Solution
The documentation for the date filter explains why this happens. It's expecting the value you supply to be a Date
object, a date string, or a number in milliseconds.
Here is their description:
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.
The reason you are getting 1970 is b/c the date
filter is taking your year, 2017, and interpreting it as the number of miliseconds since the epoch or unix time.
To make the date
filter work, you can just convert your year value into a Date
(or similar approach when using moment):
var date = new Date(obj.year, 0,1); // Jan 1
Answered By - Sunil D.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.