【问题标题】:JodaTime equivalent of DateUtils.truncate()JodaTime 相当于 DateUtils.truncate()
【发布时间】:2011-05-07 05:29:46
【问题描述】:

我以前从未使用过JodaTime,但回答这个问题时,How to get ordinal Weekdays in a Month

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

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 中做这件事的首选习惯用法是什么?

【问题讨论】:

    标签: java 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()
    

    【讨论】:

    • 迄今为止我认为最好的。我需要用用户选择的东西“四舍五入”日期。使用 [code]input.property().roundFloorCopy()[/code] 节省了大量自定义编码。
    【解决方案2】:

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

    日期时间 startOfMonth = input.withDayOfMonth(1).withMillisOfDay(0);

    【讨论】:

    • 博卓的回答可能是“官方”解决方案,但我更喜欢这个。谢谢。
    • 你为什么会这样想?我不明白。我也更喜欢这个,因为它需要创建最少数量的对象。
    • 我为什么会这样想?因为存在专门针对此类问题的类。
    • 我会说 withMillisOfDay 方法可以解决这类问题。 DateMidnight 类存在于其他类型的问题中,您希望保留对这些对象的引用。使用另一个类而必须立即将其转换回来是很愚蠢的——尤其是当您使用的类有一个完全符合您要求的方法时。
    • 两个答案都构造了相同数量的对象
    【解决方案3】:

    看看DateMidnight

    DateTime startOfMonth = new DateTime(new DateMidnight(input.withDayOfMonth(1)));
    

    更新:JodaStephen 于 2013 年 8 月 16 日发布:Joda-Time 的 2.3 版弃用了 DateMidnight,因为它是一个非常糟糕的类。

    所以使用:

    DateTime startOfMonth = input.withDayOfMonth(1).withTimeAtStartOfDay();
    

    【讨论】:

    • 所以我猜你的意思是:new DateMidnight(new DateTime())
    • @Erick 是的,但恕我直言,这不是投反对票的理由。这仍然是一个很好的答案
    • 我不明白为什么这是一个比使用withMillisOfDay(0) 更好的答案。 DateMidnight 对象不是 DateTime 对象,因此需要以这种方式创建一个额外的对象。
    • DateMidnight 应避免使用,因为它的语义不可靠(并非所有位置在 DST 更改日都有午夜)。使用 LocalDate 而不是 DateMidnight。 Joda-Time 中的预期机制是 roundFloorCopy(),Soundlinks 回答。
    【解决方案4】:

    Joda Time 还支持DateTime 类型中的withFields 方法。这也可以用来创建一个简短的语法:

    new DateTime().withDayOfMonth(1).withFields(new LocalTime(0, 0));
    

    在生产代码中,withFields 的参数应该被分解为一个常量。

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多