JodaTime相当于DateUtils.truncate()

Sea*_*oyd 41 java jodatime

我之前从未使用过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
Run Code Online (Sandbox Code Playgroud)

共享/郎相当于使用DateUtils

Date startOfMonth = DateUtils.truncate(input, Calendar.MONTH);
Run Code Online (Sandbox Code Playgroud)

在JodaTime中,首选的成语是什么?

Sou*_*ink 43

您可以使用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()
Run Code Online (Sandbox Code Playgroud)


Eri*_*son 41

使用该withMillisOfDay()方法缩短语法.

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

  • 我会说'withMillisOfDay`方法存在于这种确切的问题."DateMidnight"类存在于某些其他类型的问题中,您希望保留对这些对象的引用.使用另一个类只是为了立即将其转换回来是很愚蠢的 - 特别是当你正在使用的类有一个方法可以完全满足你所需要的时候. (3认同)

Boz*_*zho 21

看看DateMidnight.

DateTime startOfMonth = new DateTime(new DateMidnight(input.withDayOfMonth(1)));
Run Code Online (Sandbox Code Playgroud)

更新:2013-08-16作者:JodaStephen:Joda-Time的2.3版本弃用了,DateMidnight因为它是一个非常糟糕的类.

所以使用:

DateTime startOfMonth = input.withDayOfMonth(1).withTimeAtStartOfDay();
Run Code Online (Sandbox Code Playgroud)

  • 我不明白为什么这比使用`withMillisOfDay(0)`更好的答案."DateMidnight"对象不是"DateTime"对象,因此需要以这种方式创建额外的对象. (2认同)
  • 应避免使用DateMidnight,因为它具有狡猾的语义(并非所有位置都在DST更改日的午夜).使用LocalDate而不是DateMidnight.Joda-Time的预期机制是roundFloorCopy(),Soundlinks回答. (2认同)