有没有一种简单的方法可以在 Joda Time 中进入以人为中心的风格时期?
例如,如果我想要最后 4 天,我的意思是,给我一个周期(或间隔可能更合适)3 天,以及当前正在进行的日期到当前时间。所以我预计,到当前时间的间隔为 1 天、1 天、1 天、n 毫秒。
或者对于过去 5 周,请给我完整的 4 周以及截至当前时间的当前进行中的周。
我花了一些时间来解决这个问题,困难的部分是尝试将一个时期“规范化”为人类对时期结束的定义。因此,对于今天的日期,您需要标准化为一天的开始(始终是午夜),然后找到该时间与现在之间的间隔。对于非常棘手的月份,您需要标准化到月初并转到现在...等等。为了使这变得更加困难,我试图避免使用特定时期的标准化逻辑编写一个巨大的案例声明我正在绞尽脑汁试图找到一种通用的方法。
这是我当前的代码(在 Groovy 中)
static List generatePreviousIntervals(BaseSingleFieldPeriod period,
int count,
DateTime end = DateTime.now()) {
if (count < 1) {
return []
}
def intervals = []
Interval last
count.times {
def finish = last?.start ?: end
def next = new Interval(period, finish)
intervals.add(next)
last = next
}
// reverse so intervals are in normal progression order
intervals.reverse()
}
这是 Joda Time 可以轻松做到的事情吗?或者我是否必须有很多关于手滚动特定时间间隔的逻辑?
最佳答案
这就是我最终所做的,我不够聪明,无法避免使用 case 语句,但幸运的是我使用了少量的句点类型,所以它没有我想象的那么大,
/**
* Reset Joda DateTime by normalize it back to the beginning of the period
*/
static DateTime resetDate(BaseSingleFieldPeriod period,
DateTime date) {
LocalDate out = new LocalDate(date)
switch (period) {
case Years.ONE:
out = out.withMonthOfYear(1).withDayOfMonth(1)
break;
case Months.ONE:
out = out.withDayOfMonth(1)
break;
case Weeks.ONE:
// adjust day of week because Joda uses ISO standard Monday
// as start of the week
out = out.withDayOfWeek(1).minusDays(1)
break;
case Days.ONE:
// nothing to for days as we have already removed time by
// converting to local date
break;
default:
throw new UnsupportedOperationException("Unsupported period $period")
}
// convert to date minute to avoid giving specific time
out.toDateMidnight().toDateTime()
}
如果有人有更优雅的解决方案,请告诉我。
关于java - 如何在 Joda Time 中获取进度周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17171284/