Java JodaTime 相当于 DateUtils.truncate()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4133682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:57:41  来源:igfitidea点击:

JodaTime equivalent of DateUtils.truncate()

javajodatime

提问by Sean Patrick Floyd

I have never used JodaTimebefore, but answering this question, How to get ordinal Weekdays in a Month.

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

I tried it and came up with this ugly code to unset all fields below day:

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

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

Where the Commons / Langequivalent using DateUtilswould be

共享/郎相当于使用DateUtils

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

What's the preferred idiom to do that in JodaTime?

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

采纳答案by Soundlink

You can use roundFloorCopy()to mimic DateUtils.truncate

您可以使用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()

回答by Bozho

Take a look at DateMidnight.

看看DateMidnight

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

Update: 2013-08-16 by JodaStephen: Version 2.3 of Joda-Time deprecates DateMidnightas it was a very bad idea of a class.

更新:2013-08-16 由 JodaStephen:Joda-Time 2.3 版已弃用,DateMidnight因为它是一个非常糟糕的类想法。

So use:

所以使用:

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

回答by Erick Robertson

Use the withMillisOfDay()method to shorten the syntax.

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

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

回答by SpaceTrucker

Joda Time also supports the withFieldsmethod in the DateTimetype. This can also be used to create a short syntax:

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

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

In production code the argument to withFieldsshould be factored out to a constant.

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