2

有没有一种简单的方法可以在 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 可以轻松做到的事情吗?还是我必须有很多关于手动滚动特定时间间隔的逻辑?

4

2 回答 2

2

这就是我最终做的事情,我不够聪明,无法避免使用案例陈述,但幸运的是我使用了少量的句号类型,所以它没有我想象的那么大,

/**
 * 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()
}

如果有人有更优雅的解决方案,请告诉我。

于 2013-06-19T15:24:32.257 回答
0

听起来你需要一个间隔:http: //joda-time.sourceforge.net/apidocs/org/joda/time/Interval.html

并使用减法。(是的,很简单,与普通的 java 日期/日历相比非常简单)

要获得一天中的时间:

int hour = dt.getHourOfDay();
int min = dt.getMinuteOfHour();
int sec = dt.getSecondOfMinute();
于 2013-06-18T14:29:58.000 回答