1

How can I get the 15th and last day of the month in Joda time in a loop?

This is the code looks like:

DateTime initDate = new DateTime(2015,1,31,0,0);

for(int i = 0; i > 4; i++){
  initDate = initDate.plusDays(15);

   System.out.println(initDate.toString("yyyy-MM-dd");
}

I just want the result to be like this:

2015-2-15
2015-2-28
2015-3-15
2015-3-30
Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
  • this surely will help: http://stackoverflow.com/questions/9711454/how-to-get-the-last-date-of-a-particular-month-with-jodatime – blurfus Apr 01 '15 at 00:20

3 Answers3

2
for(int i = 0; i < 4; i++){ 
            initDate = initDate.plusMonths(1);
            initDate = initDate.withDayOfMonth(15);
            System.out.println(initDate.toString("yyyy-MM-dd"));
            System.out.println(initDate.dayOfMonth().withMaximumValue().toString("yyyy-MM-dd"));
        }

Something like that?

alias_boubou
  • 206
  • 6
  • 11
  • Might not do what you think it does. After all, the Maximum value of February is 29th, which is only correct about 25% of the time. – Edwin Buck Apr 01 '15 at 00:23
  • @EdwinBuck The answer is correct. The (elegant) method `withMaximumValue()` depends on context as you can easily verify yourself. – Meno Hochschild Apr 01 '15 at 08:25
1

The loop is fine but instead of adding days, you could add a month directly (have a look at http://joda-time.sourceforge.net/key_period.html and http://joda-time.sourceforge.net/apidocs/org/joda/time/Months.html) and than to get the last day of the month you can use

yourcurrentDate.dayOfMonth().withMaximumValue()
Ueli Hofstetter
  • 2,409
  • 4
  • 29
  • 52
0

You can't get the last day of the month by adding a fixed number of days, because all months don't have the same length in days.

Instead, use your loop like so

for (each month) {
   set the month appropriately (set not add)
   get the 15th day of this month (set not add)
   print the 15th day
   set the next month
   set the 1st day of the "next" month
   subtract a day
   print the "last" day
}
Edwin Buck
  • 69,361
  • 7
  • 100
  • 138