一年中两个日期之间的间隔时间
Interval period beetwen two date in a year
我必须实现 returns(逐月)过去 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);
}
一个更简单的解决方案是不创建大量 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);
}
我必须实现 returns(逐月)过去 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);
}
一个更简单的解决方案是不创建大量 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);
}