Martin Schlagnitweit
Martin Schlagnitweit

Reputation: 2101

How to build first and last of month as timestamp, with given timestamp?

Assuming a given Timestamp timestamp:

I am using Joda Time to build the first day of the month:

DateTime dateTime = new DateTime(timestamp);    
MutableDateTime firstOfMonth = dateTime.toMutableDateTime();
firstOfMonth.setDayOfMonth(1);
firstOfMonth.setTime(0, 0, 0, 0);

and the last day of the month:

MutableDateTime lastOfMonth = firstOfMonth.toMutableDateTime();
lastOfMonth.addMonths(1);
lastOfMonth.addMillis(-1);

But I wondered that calculating firstOfMonth and lastOfMonth this needs so much code. Is there a cleaner way?

Upvotes: 0

Views: 972

Answers (1)

Jiri Kriz
Jiri Kriz

Reputation: 9292

I found this in the documentation

DateTime dt = ...
DateTime firstDayOfMonth = dt.dayOfMonth().withMinimumValue();
DateTime lastDayOfMonth = dt.dayOfMonth().withMaximumValue();

Upvotes: 1

Related Questions