JodaTime 相当于 DateUtils.truncate()

2022-09-01 00:22:27

我以前从未使用过JodaTime,但回答这个问题,如何在一个月内获得序数工作日

我尝试了一下,想出了这个丑陋的代码来取消设置以下所有字段:

DateTime startOfMonth =
    input.withDayOfMonth(1)
        .withHourOfDay(0)       // there
        .withMinuteOfHour(0)    // has got to
        .withSecondOfMinute(0)  // be a shorter way
        .withMillisOfSecond(0); // to do this

使用DateUtilsCommons / Lang等效物将是

Date startOfMonth = DateUtils.truncate(input, Calendar.MONTH);

在JodaTime中这样做的首选成语是什么?


答案 1

您可以使用 roundFloorCopy() 来模仿 DateUtils.truncate

Date truncateMonth = DateUtils.truncate(input, Calendar.MONTH);
-> DateTime truncateMonth = input.dayOfMonth().roundFloorCopy();

Date truncateMinute = DateUtils.truncate(input, Calendar.MINUTE);
-> DateTime truncateMinute = input.minuteOfDay().roundFloorCopy();

Date truncateHourOfDay = DateUtils.truncate(input, Calendar.HOUR_OF_DAY);
-> DateTime truncateHourOfDay = input.hourOfDay().roundFloorCopy()

答案 2

使用 withMillisOfDay() 方法缩短语法。

DateTime startOfMonth = input.withDayOfMonth(1).withMillisOfDay(0);

推荐