JodaTime equivalent of DateUtils.truncate()

前端 未结 4 939
慢半拍i
慢半拍i 2020-12-05 09:38

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

I tried it and came up with this ugly code to unset all fiel

相关标签:
4条回答
  • 2020-12-05 09:50

    Use the withMillisOfDay() method to shorten the syntax.

    DateTime startOfMonth = input.withDayOfMonth(1).withMillisOfDay(0);
    
    0 讨论(0)
  • 2020-12-05 09:50

    Take a look at DateMidnight.

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

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

    So use:

    DateTime startOfMonth = input.withDayOfMonth(1).withTimeAtStartOfDay();
    
    0 讨论(0)
  • 2020-12-05 10:00

    You can use roundFloorCopy() to mimic 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()
    
    0 讨论(0)
  • 2020-12-05 10:06

    Joda Time also supports the withFields method in the DateTime type. This can also be used to create a short syntax:

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

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

    0 讨论(0)
提交回复
热议问题