1

I'm looking for any way to create a fixed day to month using JodaTime. I have a JSpinner to set integer values and I want get this value and create the Date. For example: JSpinner has 15, I want to create the date 2016-09-15, 2016-10-15, 2016-11-15.

How could I do this using JodaTime ?

FernandoPaiva
  • 4,410
  • 13
  • 59
  • 118

1 Answers1

7

java.time

The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. The java.time framework is built into Java 8 and later.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

java.time.LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

You can specify the year, month, and day-of-month.

LocalDate ld = LocalDate.of( 2016 , 1 , 15 );

You can switch months. The java.time classes use the Immutable Objects pattern, so a new fresh object is generated based on values of the original.

LocalDate september = ld.withMonth( 9 ); // 1-12 for January-December.

You can add/subtract months.

LocalDate nextMonth = ld.plusMonths( 1 );
LocalDate priorMonth = ld.minusMonths( 1 );

You can take any LocalDate and adjust the day to the 15th.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
LocalDate fifteenthThisMonth = today.withDayOfMonth( 15 );

Trap for a DateTimeException being thrown in the case of a day-of-month number invalid for that month, such as 31 for February.

By the way, you may find the YearMonth or MonthDay classes handy, and the Month enum too.

Joda-Time

If you must use Joda-Time, it offers a LocalDate class quite similar to java.time.LocalDate.

LocalDate ld = new LocalDate( 2016 , 1 , 7 );
LocalDate fifteenthSameMonth = ld.withDayOfMonth( 15 );
Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154