Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude 29 February from time interval

I want to exclude 29th February from my calculations of no of complete days between two dates. Excluding the corner values of the interval.

Test scenarios :

1 March 2012 - 28th February 2012  = should give 0 days.
1 March 2012 - 26th February 2012  = should give 2 days.
1 March 2013 - 28th February 2012  = should give 365 days and not 366 days.
1 March 2017 - 28th February 2012  = should give 365*5 =1825 days and not 1827 days.

Currently I parse year and check if there is any leap year between dates and then check if the interval has 29th February. Is there any way to figure if any particular interval has a particular day and number of occurrences if the interval spans over no of years.

like image 845
Hulk Avatar asked Oct 23 '22 09:10

Hulk


2 Answers

The following Java-esque pseudo-code should work. It would also allow you to add other filters if you wish:

int daysExcludingLeapYearDay(Date start, Date end)
{
    if(end.isBefore(start))
    {
        return filterOutLeapYearDays(daysBetween(end, start)).size();
    }

    return filterOutLeapYearDays(daysBetween(start, end)).size();
}

List<Date> filterOutLeapYearDays(List<Date> days)
{
    List<Date> daysExcludingLeapYearDays = 
             days
             .filter(d -> !isFeb29(d))
             .toList());

    return daysExcludingLeapYearDays;
}

List<Date> daysBetween(Date start, Date end) 
{
    List<Date> days = new List();

    for (Date day = start; day.isBefore(end); day = day.plusOneDay()) 
    {
        days.add(day);
    }

    return days
}

boolean isFeb29(Date date) 
{
    return date.month == FEBRUARY && date.day == 29;
}
like image 62
Stuart Avatar answered Oct 27 '22 00:10

Stuart


but it isn't caused by feb 29th, it's right.

if you compare 1 March 2012 and 28th February 2012 will return 1 day, and with 29th will return 2 days. The difference between these two dates is one day.

To return 0 days how you want you should compare two same dates, like 1 March 2012 and 1 March 2012.

I think you're mistaking that ^^.

like image 37
Cechinel Avatar answered Oct 27 '22 00:10

Cechinel