Maxim Veksler Maxim Veksler - 4 months ago 19
Java Question

In Joda-Time, set DateTime to start of month

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?

Answer

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

Comments