Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
Maxim Veksler Avatar asked Feb 14 '10 14:02

Maxim Veksler


1 Answers

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 - https://www.joda.org/joda-time/apidocs/overview-summary.html

like image 139
Lachlan Roche Avatar answered Sep 17 '22 14:09

Lachlan Roche