当前位置: 动力学知识库 > 问答 > 编程问答 >

angularjs - Angular date filter and moment js return the year '1970' when formatting a year

问题描述:

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

网友答案:

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
网友答案:

The reason why {{obj.year | date : 'yy'}} outputs 70 is because you are passing the number 2017 to angular's date filter and so doing the equivalent of new Date(2017) which returns a date and time that is 2017 milliseconds from 1970-01-01 00:00:00:000 or to be precise 1970-01-01 00:00:02:017. So when you run that through angular's date filter with the yy formatting string you get the last two digits of the year which is of course 70.

To offer an alternative solution, you could use angular's limiTo filter:

{{ obj.year | limitTo : 2 : 2 }}
网友答案:

As other answers stated you are getting 70 instead of 17 because angular date filter accepts:

Date object, milliseconds (string or number) or various ISO 8601 datetime string

So your input is interpreted as number of milliseconds since 1 January 1970 00:00:00, basically it is equivalent to:

console.log(new Date(2017)); // 1970-01-01T00:00:02.017Z
分享给朋友:
您可能感兴趣的文章:
随机阅读: