0👍
Since you’ve a well-formed date string, you can initialize a date object from the string and call getFullYear()
on it:
var date = new Date("2010-01-01T00:00:00.000Z");
console.log(date.getUTCFullYear());
You can try creating a year key like this in the collection, and use the key in the template:
success: function(e) {
if (e.status == 1) {
vm.data = e.data;
vm.data.forEach(item => {
var date = new Date(item.orDate);
item.year = date.getUTCFullYear();
});
...
}
In your template, instead of orDate
, show year
instead.
{{aln.year}}
Edit 1:
As @bbsimonbb pointed out the problem with getFullYear()
, I’ve updated my code to use getUTCFullYear()
instead.
1👍
I think you have 2 choice:
"2010-01-01T00:00:00.000Z".slice(0,4)
new Date("2010-01-01T00:00:00.000Z").getFullYear()
1👍
BEWARE THE TIMEZONE. The accepted answer falls into the trap! Set your device timezone to anything minus (west of london) and you’ll get 2009.
By far the safest way to recover a year from an ISO date string is .substring(0,3)
. If you want to rehydrate your date into a date object, to format it, compare it or do arithmetic, then you need to be super carefull to avoid getting a timezone when serializing/displaying.
0👍
you can simply give like this.
<div id="app">
<div v-for="aln in data">
{{aln._id}}
{{aln.no}}
{{new Date(aln.orDate).getFullYear()}}
</div>
</div>