Java 间隔期为一年中的两个日期

Java 间隔期为一年中的两个日期,java,date,datetime,jodatime,gregorian-calendar,Java,Date,Datetime,Jodatime,Gregorian Calendar,我必须实现一个函数,按月返回过去12个月的开始日期和最终日期。例如: 因此,今年5月,我想展示: 2016年05月01日00:00:00:000T/30/04/2017 23:59:59:999T 我创建了以下函数,想问这是否正确,或者是否有其他更简单的解决方案 public Interval getPeriod() { MutableDateTime fromDateTime = new MutableDateTime(new DateTime().withTimeAtStartOfD

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

因此,今年5月,我想展示:

2016年05月01日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);
}

一个更简单的解决方案是不创建大量可变DateTime实例,只使用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);
}

看看Moment.jsI,我不喜欢使用外部脚本,也不喜欢每隔几个小时使用一次。如果你有澄清,请编辑原文。谢谢你的回答,这比我的解决方案简单多了