views:

345

answers:

2

Hello,

My API allows library client to pass Date:

method(java.util.Date date)

Working with joda-time, from this date I would like to extract the month and iterate over all days this month contains.

Now, the passed date is usually new Date() - meaning current instant. My problem actually is setting the new DateMidnight(jdkDate) instance to be at the start of the month.

Could someone please demonstrates this use case with joda-time.

Thank you, Maxim.

+4  A: 

Midnight at the start of the first day of the current month is given by:

// first midnight in this month
DateMidnight first = new DateMidnight().withDayOfMonth(1);

// last midnight in this month
DateMidnight last = first.plusMonths(1).minusDays(1);

If starting from a java.util.Date, a different DateMidnight constructor is used:

// first midnight in java.util.Date's month
DateMidnight first = new DateMidnight( date ).withDayOfMonth(1);

Joda Time java doc - http://joda-time.sourceforge.net/api-release/index.html

Lachlan Roche
btw, on that "last" why not: DateMidnight last = first.plusMonths(1).minusDays(1); Same thing,just cleaner.
Maxim Veksler
+1  A: 

Oh, I did not see that this was about jodatime. Anyway:

Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);

int min = c.getActualMinimum(Calendar.DAY_OF_MONTH);
int max = c.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = min; i <= max; i++) {
    c.set(Calendar.DAY_OF_MONTH, i);
    System.out.println(c.getTime());
}

Or using commons-lang:

Date min = DateUtils.truncate(date, Calendar.MONTH);
Date max = DateUtils.addMonths(min, 1);
for (Date cur = min; cur.before(max); cur = DateUtils.addDays(cur, 1)) {
    System.out.println(cur);
}
Thanks for the java basic api note. I've learned from this as well.
Maxim Veksler