Reputation: 11
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
Upvotes: 1
Views: 1000
Reputation: 70959
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
}
Upvotes: 0
Reputation: 206
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?
Upvotes: 2
Reputation: 2534
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()
Upvotes: 1