间隔期是一年中的两个日期

时间:2017-05-23 12:53:02

标签: java date datetime jodatime gregorian-calendar

我必须实现一个函数,它返回(月到月)过去12个月的开始日期和最终日期。例如:

今年5月,我希望结果显示:

  

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

我创建了以下函数,想问这是否正确或是否有另一个更简单的解决方案?

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);
}

1 个答案:

答案 0 :(得分:1)

更简单的解决方案是不创建大量MutableDateTime个实例并仅使用DateTime的方法:

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);
}