间隔期beetwen一年中的两个日期
问题描述:
我必须实现一个函数,该函数返回(月至月)最近12个月的开始日期和最终日期。例如:间隔期beetwen一年中的两个日期
今年五月我想显示的结果:
2016年1月5日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);
}
+1
感谢这个答案,它比我的解决方案容易 –
看看Moment.js – Chris
我不喜欢使用外部脚本 –
待办事项每隔几个小时不要[转贴问题](https://stackoverflow.com/q/44137505/642706)。如果您有澄清,请编辑原件。 –