The goal is to use Javascript to UNIQUELY calculate the total years of a person's work experience, from an array of Date Ranges of the person's work history. There are Date Ranges which overlap (meaning, the person had multiple jobs within the overlapping period). Here is an example below and the date format is yyyy-mm-dd;
- 2001-02-01 to 2009-03-01
- 2004-06-01 to 2020-08-01
- 2005-04-01 to 2021-03-01
- 2008-07-01 to 2016-06-01
From the date ranges above, there are overlapping work dates. The correct computation of the person's years of work experience should be 20 years.
The problem I have is to creating an algorithm that can put into account, the overlapping periods within the person's four work histories and not count them as separate years of work experience E.g just summing up the years between each of the four job dates gives 48 years WHICH IS INCORRECT (The experience was over a 20-year period).
var time_diff=0, yrs_diff=0;
var jobExperience = [
{date_began:'2001-02-01', date_ended:'2009-03-01'},
{date_began:'2004-06-01', date_ended:'2020-08-01'},
{date_began:'2005-04-01', date_ended:'2021-03-01'},
{date_began:'2008-07-01', date_ended:'2016-06-01'}
];
for(let i=0; i<jobExperience.length; i++){
let date_1, date_2;
let began = jobExperience[i].date_began.split('-');
let ended = jobExperience[i].date_ended.split('-');
date_1 = new Date(began[1]+'/'+began[2]+'/'+began[0]);
date_2 = new Date(ended[1]+'/'+ended[2]+'/'+ended[0]);
time_diff += date_2.getTime() - date_1.getTime();
}
yrs_diff = parseInt(time_diff/(1000 * 3600 * 24 * 365));
console.log(yrs_diff);
The snippet above only just blindly adds up the years between each record of work history (This is not correct). Where I need some help is a clue or better still pseudocode or complete code on how to sum up the years between each record of work history but account for overlaps between work history dates and by so doing, overlapping periods are only counted once.