Search code examples
javadatedatetimejodatimegregorian-calendar

Interval period beetwen two date in a year


I have to implement a function that returns (month to month) the starting date and the final date of the last 12 months. For example:

In May of this year I want to show as a result:

01/05/2016 00: 00: 00: 000T / 30/04/2017 23: 59: 59: 999T.

I created the following function, wanted to ask if this is correct or is there another simpler solution?

public Interval getPeriod() {
    MutableDateTime fromDateTime = new MutableDateTime(new DateTime().withTimeAtStartOfDay());
     fromDateTime.addMonths(-12); // Start Month        
     fromDateTime.setDayOfMonth(1); // First day start month

    MutableDateTime toDateTime = new MutableDateTime(new DateTime().withTimeAtStartOfDay());
    toDateTime.addMonths(-1); // last month
    toDateTime.setDayOfMonth(1); // firt day last month

    DateTime firstDayStart = fromDateTime.toDateTime();

    DateTime firstDayLastMonth = toDateTime.toDateTime();
    DateTime lastDayLastMonth = firstDayLastMonth.dayOfMonth().withMaximumValue();
    DateTime lastInstantLastMonth = lastDayLastMonth.withTime(23, 59, 59, 999);
    log.debug("start: {} end: {}",firstDayStart, lastInstantLastMonth);
    return new Interval(firstDayStart, lastInstantLastMonth);
}

Solution

  • A simpler solution would be to not create lots of MutableDateTime instances and use only DateTime's methods:

    public Interval getPeriod() {
        DateTime d = new DateTime(); // current date
        DateTime start = d.withDayOfMonth(1).minusMonths(12) // day 1 of 12 months ago
                          .withTimeAtStartOfDay(); // start date
        DateTime end = d.minusMonths(1) // previous month
                        .dayOfMonth().withMaximumValue() // last day of month
                        .withTime(23, 59, 59, 999); // end date
    
        return new Interval(start, end);
    }