Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JodaTime equivalent of DateUtils.truncate()

Tags:

java

jodatime

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 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 / Lang equivalent using DateUtils would be

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

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

like image 619
Sean Patrick Floyd Avatar asked Nov 09 '10 12:11

Sean Patrick Floyd


People also ask

What does Dateutils truncate do?

Truncate this date, leaving the field specified as the most significant field. Determines how two calendars compare up to no more than the specified most significant field. Determines how two dates compare up to no more than the specified most significant field.

What is Jodatime in Java?

Joda-Time provides a quality replacement for the Java date and time classes. Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java. time (JSR-310). Joda-Time is licensed under the business-friendly Apache 2.0 licence.


2 Answers

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() 
like image 123
Soundlink Avatar answered Sep 23 '22 13:09

Soundlink


Use the withMillisOfDay() method to shorten the syntax.

 DateTime startOfMonth = input.withDayOfMonth(1).withMillisOfDay(0); 
like image 22
Erick Robertson Avatar answered Sep 22 '22 13:09

Erick Robertson