Reputation: 799
I have an array like this
var array = [
{ date:2014-11-11,
title:test },
{ date:2014-11-12,
title:test },
{ date:2014-11-13,
title:test },
…more
…more
{ date:2015-01-01
title:test},
{ date:2015-01-02
title:test},
…more
…more
{ date:2015-03-01
title:test}
]
My questions is how to get the total month of each year. For example, I need to have 2 months (nov to dec) in 2014 and 3 months (Jan to March) in 2015.
var firstYear = parseInt($filter('date')(array[0].date, 'yyyy'));
var lastYear = parseInt($filter('date')(array[array.length-1].date, 'yyyy'));
I am not sure what I can do next to get the total month of the year
Can anyone help me about it? Thanks!
Upvotes: 0
Views: 68
Reputation: 147413
Your array syntax is not valid javascript. Do you really have date strings like:
date: '2014-11-11',
or is the value a Date object representing that date? Is the date local or UTC? Anyway, I'll assume you have strings and whether they are UTC or local doesn't matter.
My questions is how to get the total month of each year. For example, I need to have 2 months (nov to dec) in 2014 and 3 months (Jan to March) in 2015.
I'm not exactly sure what you want, you should provide an example of your expected output. The following returns the month ranges in particular years, there is no conversion of Strings to Dates:
// Sample data
var array = [
{ date:'2014-11-11',
title:'test'},
{ date:'2014-11-12',
title:'test'},
{ date:'2014-11-13',
title:'test'},
{ date:'2015-01-01',
title:'test'},
{ date:'2015-01-02',
title:'test'},
{ date:'2015-03-01',
title:'test'}
];
And the function:
function getMonthCount2(arr) {
var yearsMonths = arr.map(function(v){return v.date.substr(0,7).split(/\D/)}).sort();
var monthRanges = {}
yearsMonths.forEach(function(v,i) {
if (monthRanges[v[0]]) {
monthRanges[v[0]] += v[1] - yearsMonths[--i][1];
} else {
monthRanges[v[0]] = 1;
}
});
return monthRanges;
}
console.log(getMonthCount2(array)); // {'2014': 2, '2015': 3}
The above assumes valid input, you may want to put in a validation step to ensure the data is clean before passing it to the function.
Upvotes: 1
Reputation: 13125
If you're dealing with dates and times you should probably think about using a library as there are many nuances that go along with working dates and times.
I just did something similar to this and I solved it using moment js and the date range extension.
Looking at the docs for moment-range it seems that you can do something like this:
var start = new Date(2012, 2, 1);
var end = new Date(2012, 7, 5);
var range1 = moment().range(start, end);
range1.by('months', function(moment) {
// Do something with `moment`
});
Upvotes: 0