When I use these codes, I get dates of the month which we are in. For instance, I can see dates between from 01/09/2017 to 21/09/2017.
private void createRandomData(InMemoryCursor cursor) {
List<Object[]> data = new ArrayList<>();
Calendar today = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
today.set(Calendar.HOUR_OF_DAY,0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
mStart = (Calendar) today.clone();
mStart.set(Calendar.DAY_OF_MONTH, 1);
while (mStart.compareTo(today) <= 0) {
data.add(createItem(mStart.getTimeInMillis()));
mStart.add(Calendar.DAY_OF_MONTH, 1);
}
cursor.addAll(data);
}
However, I need dates of the particular month. How can I see other dates which in other months? For example, I want to see dates of April. It should not be September. (I know it's related to today.clone() but I didn't understand how can I change it).
I plan to separate months with dialog in Android studio and when I select any month, I should see all of dates of month.
I need just dates of a month for doing this, like April. How can I get dates of April? (If I get dates of April, I can do this all of the months)
EDIT Some changing and results:
private void createRandomData(InMemoryCursor cursor) {
List<Object[]> data = new ArrayList<>();
Calendar today = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
today.set(Calendar.HOUR_OF_DAY,0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
mStart = (Calendar) today.clone();
mStart.set(Calendar.MONTH, Calendar.APRIL);
mStart.set(Calendar.DAY_OF_MONTH, 1);
data.add(createItem(mStart.getTimeInMillis()));
cursor.addAll(data);
}
I get just 01/04/2017
private void createRandomData(InMemoryCursor cursor) {
List<Object[]> data = new ArrayList<>();
Calendar today = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
today.set(Calendar.HOUR_OF_DAY,0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
mStart = (Calendar) today.clone();
mStart.set(Calendar.MONTH, Calendar.APRIL);
int daysInMonth = today.getActualMaximum(Calendar.DAY_OF_MONTH);
for(int i=0; i<daysInMonth; i++ ){
mStart.set(Calendar.DAY_OF_MONTH, i);}
data.add(createItem(mStart.getTimeInMillis()));
cursor.addAll(data);
}
I get just 29/04/2017 and If I change mStart.set(Calendar.DAY_OF_MONTH, i) to mStart.set(Calendar.DAY_OF_MONTH, 1) result is 01/04/2017
To get all the dates of a particular month, set the Calendar to a date in that month, e.g. the 1th, ask the Calendar for the number of dates in that month, then get the dates.
You could also just get dates until month changes, but code below ask for number of days in the month, to show how you can do that.
This code just prints the dates. You can of course do whatever you want with them instead.
public static void printDatesInMonth(int year, int month) {
SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(year, month - 1, 1);
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = 0; i < daysInMonth; i++) {
System.out.println(fmt.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
Test
printDatesInMonth(2017, 2);
Output
01/02/2017
02/02/2017
03/02/2017
04/02/2017
05/02/2017
06/02/2017
07/02/2017
08/02/2017
09/02/2017
10/02/2017
11/02/2017
12/02/2017
13/02/2017
14/02/2017
15/02/2017
16/02/2017
17/02/2017
18/02/2017
19/02/2017
20/02/2017
21/02/2017
22/02/2017
23/02/2017
24/02/2017
25/02/2017
26/02/2017
27/02/2017
28/02/2017
#Andreas's answer provides the way to do it with Calendar. I just like to add another approach.
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it here).
First you can use a org.threeten.bp.YearMonth to represent the month and year (in this case, April 2017). Then you loop through all the days of this month.
The getTimeInMillis() method takes the number of milliseconds since epoch (1970-01-01T00:00Z), and in your code you're getting it from the date at midnight, in the JVM default timezone.
In ThreeTen Backport, you do this by converting the YearMonth to a org.threeten.bp.LocalDate, then convert it to the JVM default timezone (using a org.threeten.bp.ZoneId), and then using the resulting org.threeten.bp.ZonedDateTime to get the epoch millis value:
// April 2017
YearMonth ym = YearMonth.of(2017, 4);
// get the last day of month
int lastDay = ym.lengthOfMonth();
// loop through the days
for(int day = 1; day <= lastDay; day++) {
// create the day
LocalDate dt = ym.atDay(day);
// set to midnight at JVM default timezone
ZonedDateTime z = dt.atStartOfDay(ZoneId.systemDefault());
// get epoch millis value
data.add(createItem(z.toInstant().toEpochMilli()));
}
If you also need to check if the date is before the current date, you can add an additional check:
....
// today
LocalDate today = LocalDate.now();
// loop through the days
for (int day = 1; day <= lastDay; day++) {
// create the day
LocalDate dt = ym.atDay(day);
if (dt.isBefore(today)) {
....
The use of TimeZone.getDefault() and ZoneId.systemDefault(), although might seem a good convenience, is also tricky, because the JVM default timezone can be changed without notice, even at runtime, so it's better to always make it explicit which one you're using.
The API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
Example: to use the New York timezone, you could do:
....
// New York timezone
ZoneId ny = ZoneId.of("America/New_York");
// today in New York timezone
LocalDate today = LocalDate.now(ny);
// loop through the days
for (int day = 1; day <= lastDay; day++) {
// create the day
LocalDate dt = ym.atDay(day);
if (dt.isBefore(today)) {
// set to midnight at New York timezone
ZonedDateTime z = dt.atStartOfDay(ny);
....
America/New_York is one of the valid names returned by ZoneId.getAvailableZoneIds().
java.util.Calendar
Regarding your code, you're starting with day zero and adding the item to data outside of the loop (so you're just adding the last one - indent your code and you'll see that data.add is outside of the for loop). The code should be like that:
Calendar mStart = (Calendar) today.clone();
// set day to 1
mStart.set(Calendar.DAY_OF_MONTH, 1);
// set month to April
mStart.set(Calendar.MONTH, Calendar.APRIL);
// now mStart is April 1st, we can begin the loop
// get the number of days in April
int daysInMonth = today.getActualMaximum(Calendar.DAY_OF_MONTH);
// loop from day 1 to daysInMonth
for (int i = 1; i <= daysInMonth; i++) {
// set the day
mStart.set(Calendar.DAY_OF_MONTH, i);
// add item for the day
data.add(createItem(mStart.getTimeInMillis()));
}
// add all items to cursor
cursor.addAll(data);
you are starting with today's date, so assuming you want months starting from there simply use:
cal.add(Calendar.MONTH, 1) to move to next month or
cal.add(Calendar.MONTH, -1) to move to last month.
Related
I've got a few dozen backlog requests in the pipeline like
'I need this functionality to run on the third Thursday of every month, and the first Wednesday of every other month...'
I've already got a function that runs every day, i just need the: isThirdSundayOfMonth(date) bit to append onto then end.
The less time I spend considering the nuances of the Gregorian calendar and timezones, the better my life is.
Anyone know a Java library that simplifies this sort of calculation? No xml config or frameworks or anything. Just a .Jar and a documented, readable API would be perfect.
Any help would be much appreciated.
Complete overview:
In Java-8 (new standard):
LocalDate input = LocalDate.now(); // using system timezone
int ordinal = 3;
DayOfWeek weekday = DayOfWeek.SUNDAY;
LocalDate adjusted =
input.with(TemporalAdjusters.dayOfWeekInMonth(ordinal, weekday));
boolean isThirdSundayInMonth = input.equals(adjusted);
In Joda-Time (popular 3rd-party-library):
LocalDate input = new LocalDate(); // using system timezone
int ordinal = 3;
int weekday = DateTimeConstants.SUNDAY;
LocalDate start = new LocalDate(input.getYear(), input.getMonthOfYear(), 1);
LocalDate date = start.withDayOfWeek(weekday);
LocalDate adjusted = (
date.isBefore(start))
? date.plusWeeks(ordinal)
: date.plusWeeks(ordinal - 1);
boolean isThirdSundayInMonth = input.equals(adjusted);
Using java.util.GregorianCalendar (old standard):
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
GregorianCalendar input = new GregorianCalendar();
int ordinal = 3;
int weekday = Calendar.SUNDAY;
GregorianCalendar start =
new GregorianCalendar(input.get(Calendar.YEAR), input.get(Calendar.MONTH), 1);
int dow = start.get(Calendar.DAY_OF_WEEK); // Sun=1, Mon=2, ...
int delta = (weekday - dow);
if (delta < 0) {
delta += 7;
}
start.add(Calendar.DAY_OF_MONTH, delta + (ordinal - 1) * 7);
String comp1 = sdf.format(input.getTime());
String comp2 = sdf.format(start.getTime());
boolean isThirdSundayInMonth = comp1.equals(comp2);
Even with the ugliest library a solution is possible ;-) I have used a string comparison in order to get rid of any timezone effects or time-of-day-parts including milliseconds. A field-wise comparison based only on year, month and day-of-month is also a good idea.
Using Time4J (my own 3rd-party-library):
PlainDate input =
SystemClock.inLocalView().today(); // using system timezone
Weekday weekday = Weekday.SUNDAY;
PlainDate adjusted =
input.with(PlainDate.WEEKDAY_IN_MONTH.setToThird(weekday));
boolean isThirdSundayInMonth = input.equals(adjusted);
The canonical library for all things date and time related is Joda Time. Adopt that and purge all the standard java classes like Date, Calendar, etc.
It will make your life much better.
As for "How do I use joda-time to find the third Thursday of the month", there's a stackoverflow answer for that already. I'd suggest using the code that the question asker posted and then the question "is it now the third Thursday of the month" is answered by:
LocalDate today = new LocalDate();
if (today.equals(calcDayOfWeekOfMonth(DateTimeConstants.THURSDAY, 3, today))) {
// do special third-Thursday processing here
}
This question already has answers here:
How to get the first day of the current week and month?
(15 answers)
Closed 6 years ago.
I would like to fetch the first date of a week.
My input is going to be a String type like 07/26/2014".
I need to get the first date of week in which the above date(07/26/2014) falls.
I need output date in MM/dd/YYYY format .
basically I need output as 07/21/2014.
Please give me the java program. I have done upto this
SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yy");
String date ="07/26/2014";
Date Currentdate = formatter1.parse(date);
int currentday=Currentdate.getDay();
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
int startDay=currentday-calendar.getFirstDayOfWeek();
Currentdate.setDate(contacteddate.getDate()-startDay);
System.out.println(contacteddate.getDate());
}
The above code only gives me the date.. I need date along with month and year in "MM/dd/YYYY"
Please help
I would do it this way
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
After setting time to Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
use
calendar.set(Calendar.DAY_OF_WEEK, 1)
and then
simpleFormat.format(calendar.getTime());
This will help you.
// Get calendar set to current date and time
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 1; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
The problem with all presented solutions so far is not to specify what exactly the week definition is. Week definitions are either technically specified like in ISO-8601-standard (Monday as first day of week and first calendar week of year containing at least four days), or they use localized rules (for example in US a week begins by Sunday!).
Due to the requirement that the OP wants "07/21/2014" as first day of week around "07/26/2014" it seems that ISO-8601 is what the OP really wants. But code like
Calendar calendar = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
...
will not work in a country like US or an application server located in US. Counter example:
// simulating a US-located application server where this code is running
GregorianCalendar calendar = new GregorianCalendar(Locale.US);
calendar.set(2014, Calendar.JULY, 26);
calendar.getTime(); // avoid ugly side effects in calendar date handling
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(calendar.getTime())); // output: 2014-07-20
If the OP changes the choosen locale to let's say Locale.FRANCE (applying ISO-rules) then the OP can achieve his goal using the traditional Java-date-and-time-library.
It should be noted however that week handling using the java.util.Calendar-stuff is often confusing and hard. For example: Without the strange getter-call (calendar.getTime()) which enforces update of internal calculation the result would be: 2014-07-06 (surely not what OP wants).
Therefore I recommend following other libraries to choose a generic approach compatible with different week definitions:
a) Java-8 (built-in library JSR-310 aka java.time):
LocalDate date = LocalDate.of(2014, 7, 26);
TemporalField dowField = WeekFields.ISO.dayOfWeek();
date = date.with(dowField, dowField.range().getMinimum());
System.out.println(date); // output: 2014-07-21
Note: Avoid code like date.with(DayOfWeek.MONDAY) because in that case the java.time-library cannot evaluate the underlying week rules which possibly deviate from ISO-8601 (here choosen: WeekFields.ISO, but it might also be WeekFields.SUNDAY_START).
b) my own library Time4J:
PlainDate date = PlainDate.of(2014, 7, 26);
date = date.with(Weekmodel.ISO.localDayOfWeek().minimized());
System.out.println(date); // output: 2014-07-21
c) If you know in advance that you only want ISO-8601-week-rules then you might also consider a simpler approach in Java-8 or instead its predecessor JodaTime:
// Java-8 applying ISO-8601-rules
LocalDate date = LocalDate.of(2014, 7, 26);
date = date.with(DayOfWeek.MONDAY);
// Joda-Time
LocalDate date = new LocalDate(2014, 7, 26);
date = date.dayOfWeek().withMinimumValue();
Here I want to display dates like
2013-01-01,
2013-01-02,
2013-01-03,
.
.
...etc
I can get total days in a month
private int getDaysInMonth(int month, int year) {
Calendar cal = Calendar.getInstance(); // or pick another time zone if necessary
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1); // 1st day of month
cal.set(Calendar.YEAR, year);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
Date startDate = cal.getTime();
int nextMonth = (month == Calendar.DECEMBER) ? Calendar.JANUARY : month + 1;
cal.set(Calendar.MONTH, nextMonth);
if (month == Calendar.DECEMBER) {
cal.set(Calendar.YEAR, year + 1);
}
Date endDate = cal.getTime();
// get the number of days by measuring the time between the first of this
// month, and the first of next month
return (int)((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
}
Does anyone have an idea to help me?
If you only want to get the max number of days in a month you can do the following.
// Set day to one, add 1 month and subtract a day
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.get(Calendar.DAY_OF_MONTH);
If you actually want to print every day then you can just set the day of month to 1 and keep adding a day in a loop until the month changes.
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
int myMonth=cal.get(Calendar.MONTH);
while (myMonth==cal.get(Calendar.MONTH)) {
System.out.print(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 1);
}
Modern answer: Don’t use Calendar. Use java.time, the modern Java date and time API.
YearMonth ym = YearMonth.of(2013, Month.JANUARY);
LocalDate firstOfMonth = ym.atDay(1);
LocalDate firstOfFollowingMonth = ym.plusMonths(1).atDay(1);
firstOfMonth.datesUntil(firstOfFollowingMonth).forEach(System.out::println);
Output (abbreviated):
2013-01-01
2013-01-02
2013-01-03
…
2013-01-30
2013-01-31
datesUntil gives us a stream of dates until the specified end date exclusive, so when we give it the 1st of the following month, we get exactly all the dates of the month in question. In this example case up to and including January 31.
Link: Oracle tutorial: Date Time explaining how to use java.time.
This will give you all days of a month.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(df.format(cal.getTime()));
for (int i = 1; i < maxDay; i++) {
cal.set(Calendar.DAY_OF_MONTH, i + 1);
System.out.print(", " + df.format(cal.getTime()));
}
The first date is printed outside of loop for comma separated output.
A couple of comments...
Firstly, "... Calendar objects are particularly expensive to create." (J. Bloch, Effective Java, 2nd Ed.). If this is a method that you are going to be calling frequently, consider that you do not need to create a new Calendar object every time you call it.
Consider using a Calendar object held in a private static field that is initialized with a static initializer block. This presumes a single-threaded solution and would require synchronization in a concurrent environment. Otherwise, it really ought to be possible to reuse the same Calendar for your calculations.
Secondly, while you can find that greatest value for the DAY_OF_MONTH by iterating over the possible valid values, I think you can let the API do it for you. Consider using the getMaximum(DAY_OF_MONTH) or getGreatestMaximum(DAY_OF_MONTH) methods of the Calendar class.
Write a common method like that if you are using kotlin-
fun getAllDateOfMonth(year: Int, month: Month): List<LocalDate> {
val yearMonth= YearMonth.of(year, month)
val firstDayOfTheMonth = yearMonth.atDay(1)
val datesOfThisMonth = mutableListOf<LocalDate>()
for (daysNo in 0 until yearMonth.lengthOfMonth()){
datesOfThisMonth.add(firstDayOfTheMonth.plusDays(daysNo.toLong()))
}
return datesOfThisMonth
}
And call it like that -
getAllDateOfMonth(2021,Month.MAY):
The posters here say that Date is always in UTC time. However, if I create a Date(), create a Calendar, and set the calendar time with the date, the time remains my local time (and I am not on UTC time.
I've tested this by printing out the calendar's date in a loop, subtracting an hour per loop. It's 11pm on the 19th of May here, and it takes 24 loops before the date changes to the 18th of May. It's currently 1pm UTC, so if the calendar were set properly it would only take 14 loops.
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
int index = 0;
for(; index > -30; index--)
{
System.out.println(index);
System.out.println(dateFormatter.format(calendar.getTime()));
System.out.println();
calendar.add(Calendar.HOUR, -1);
}
java.util.Calendar has a static factory method which takes a timezone.
Calendar.getInstance(java.util.TimeZone)
So you can say:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
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?
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
An alternative way (without taking DateMidnight into account) to get the first day of the month would be to use:
DateTime firstDayOfMonth = new DateTime().dayOfMonth().withMinimumValue();
First Moment Of The Day
The answer by ngeek is correct, but fails to put the time to the first moment of the day. To adjust the time, append a call to withTimeAtStartOfDay.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
org.joda.time.DateTime startOfThisMonth = new org.joda.time.DateTime().dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
org.joda.time.DateTime startofNextMonth = startOfThisMonth.plusMonths( 1 ).dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
System.out.println( "startOfThisMonth: " + startOfThisMonth );
System.out.println( "startofNextMonth: " + startofNextMonth );
When run in Seattle US…
startOfThisMonth: 2013-11-01T00:00:00.000-07:00
startofNextMonth: 2013-12-01T00:00:00.000-08:00
Note the difference in those two lines of console output: -7 vs -8 because of Daylight Saving Time.
Generally one should always specify the time zone rather than rely on default. Omitted here for simplicity. One should add a line like this, and pass the time zone object to the constructors used in example above.
// Time Zone list: http://joda-time.sourceforge.net/timezones.html (Possibly out-dated, read note on that page)
// UTC time zone (no offset) has a constant, so no need to construct: org.joda.time.DateTimeZone.UTC
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
java.time
The above is correct but outdated. The Joda-Time library is now supplanted by the java.time framework built into Java 8 and later.
The LocalDate represents a date-only value without time-of-day and without time zone. A time zone is crucial in determine a date. For any given moment the date varies by zone around the globe.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
Use one of the TemporalAdjusters to get first of month.
LocalDate firstOfMonth = today.with( TemporalAdjusters.firstDayOfMonth() );
The LocalDate can generate a ZonedDateTime that represents the first moment of the day.
ZonedDateTime firstMomentOfCurrentMonth = firstOfMonth.atStartOfDay( zoneId );
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);
}
DateMidnight is now deprecated. Instead you can do:
LocalDate firstOfMonth = new LocalDate(date).withDayOfMonth(1);
LocalDate lastOfMonth = firstOfMonth.plusMonths(1).minusDays(1);
If you know the time zone use new LocalDate(date, timeZone) instead for greater accuracy.
You can also do .dayOfMonth().withMinimumValue() instead of .withDayOfMonth(1)
EDIT:
This will give you 12/1/YYYY 00:00 and 12/31/YYYY 00:00. If you rather the last of the month be actually the first of the next month (because you are doing a between clause), then remove the minusDays(1) from the lastOfMonth calculation
You can get Start date and end date of month using this:
DateTime monthStartDate = new DateTime().dayOfMonth().withMinimumValue();
DateTime monthEndDate = new DateTime().dayOfMonth().withMaximumValue();