Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First day of next month with java Joda-Time

How would you rewrite the method below, which returns the first day of next month, with the org.joda.time package in Joda-Time?

public static Date firstDayOfNextMonth() {     Calendar nowCal = Calendar.getInstance();     int month = nowCal.get(Calendar.MONTH) + 1;     int year = nowCal.get(Calendar.YEAR);      Calendar cal = Calendar.getInstance();     cal.clear();     cal.set(Calendar.YEAR, year);     cal.set(Calendar.MONTH, month);     cal.set(Calendar.DAY_OF_MONTH, 1);     Date dueDate = new Date(cal.getTimeInMillis());      return dueDate; } 
like image 468
MatBanik Avatar asked Jan 24 '11 19:01

MatBanik


1 Answers

   LocalDate today = new LocalDate();    LocalDate d1 = today.plusMonths(1).withDayOfMonth(1); 

A little easier and cleaner, isn't it? :-)

Update: If you want to return a date:

return new Date(d1.toDateTimeAtStartOfDay().getMillis()); 

but I strongly advise you to avoid mixing pure DATE types (i.e. a day in the calendar, without time information) with DATETIME types, specially with a "physical" datetime type as is the hideous java.util.Date . It's somewhat like converting from-to integer and floating types, you must be careful.

like image 134
leonbloy Avatar answered Sep 25 '22 12:09

leonbloy