How to get all the dates in a month using calender class? - java

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):

Related

How to get all the dates in a certain month

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.

Detect invalid date on Calendar.set()

I have this method that returns me a Date() changed by one of it's "fields" (DAY, MONTH, YEAR).
public static Date getDateChanged(Date date, int field, int value) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(field, value);
return cal.getTime();
}
However, cal.set() is unable to give an exception when the field we are trying to set is not compatible with the date in question. So, in this case:
Date date = new Date();
date = getDateChanged(date, Calendar.DAY_OF_MONTH, 29);
date = getDateChanged(date, Calendar.MONTH, 1); // feb
date is, in the end, 01/03/15, because Calendar.set() detects that February can't be set with day 29, so automatically set's date to the next possible day (I thinks this is how the routine works).
This is not so bad, however, in my case,
I want to detect that the date I'm trying to build is impossible and then start decrementing the day, so in this case what I'm trying to achieve is 28/02/15, how can I do this?
Example:
29/02/15 ===> 28/02/15
You can use cal.getActualMaximum(Calendar.DAY_OF_MONTH) to find the maximum days in the given month for your calendar instance.
This way, you can handle the case you mentioned above yourself.
Also see the answer here: Number of days in particular month of particular year?
You can use:
public void setLenient(boolean lenient)
Specifies whether or not date/time interpretation is to be lenient.
With lenient interpretation, a date such as "February 942, 1996" will
be treated as being equivalent to the 941st day after February 1,
1996. With strict (non-lenient) interpretation, such dates will cause an exception to be thrown. The default is lenient.
Parameters:
lenient - true if the lenient mode is to be turned on; false if it is to be turned off.
See Also:
isLenient(), DateFormat.setLenient(boolean)
This way you get exception when you pass something wrong :)
You can check the maximum value with getActualMaximum:
public static Date getDateChanged(Date date, int field, int value) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int maximum = calendar.getActualMaximum(field);
if (value > maximum) {
value = maximum;
}
cal.set(field, value);
return cal.getTime();
}
May be this solution will help you
public static Date getDateChanged(Date date, int field, int value) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(field, value);
if (field == Calendar.MONTH && cal.get(Calendar.MONTH) != value) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int month = (cal.get(Calendar.MONTH) - 1) < 0 ? 0 : (cal.get(Calendar.MONTH) - 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DATE));
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
return calendar.getTime();
}
return cal.getTime();
}

Android get difference in milliseconds between two dates

I have Integer fields:
currentYear,currentMonth,currentDay,currentHour,currentMinute and nextYear,nextMonth,nextDay,nextHour,nextMinute.
How I can get difference between those two spots in time in milliseconds.
I found a way using Date() object, but those functions seems to be depricated, so it's little risky.
Any other way?
Use GregorianCalendar to create the date, and take the diff as you otherwise would.
GregorianCalendar currentDay=new GregorianCalendar (currentYear,currentMonth,currentDay,currentHour,currentMinute,0);
GregorianCalendar nextDay=new GregorianCalendar (nextYear,nextMonth,nextDay,nextHour,nextMinute,0);
diff_in_ms=nextDay. getTimeInMillis()-currentDay. getTimeInMillis();
Create a Calendar object for currenDay and nextDay, turn them into longs, then subtract. For example:
Calendar currentDate = Calendar.getInstance();
Calendar.set(Calendar.MONTH, currentMonth - 1); // January is 0, Feb is 1, etc.
Calendar.set(Calendar.DATE, currentDay);
// set the year, hour, minute, second, and millisecond
long currentDateInMillis = currentDate.getTimeInMillis();
Calendar nextDate = Calendar.getInstance();
// set the month, date, year, hour, minute, second, and millisecond
long nextDateInMillis = nextDate.getTimeInMillis();
return nextDateInMillis - currentDateInMillis; // this is what you want
If you don't like the confusion around the Calendar class, you can check out the Joda time library.

Date picking and finding difference

I am a novice to Java programming using Netbeans. I have added jCalendar to my GUI to pick a date.
I have entered this line in Events -> "property change" code of jCalendar button,
Date date=jcalendar1.getDate();
So that I get the date immediately when it is changed. Am I right?
The purpose:
I want to find the difference in milliseconds from the afternoon (12:00 pm) of this date above to NOW (current date and time).
There are several programs showing the date difference but all have dates hardcoded and being a newbie i do not know how to replace it with the date that is picked. (also i am confused between the objects Date and Calendar, not able to understand the difference between them). For example, a piece from here:
http://www.java2s.com/Code/Java/Data-type/ReturnsaDatesetjusttoNoontotheclosestpossiblemillisecondoftheday.htm
if (day == null) day = new Date();
cal.setTime(day);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
return cal.getTime();
Here day is a Date object. How is cal (a calendar object) linked to it to enter the time. How should the cal object be defined first? How can I use this or anything else in your opinion for my program. A piece of code with detail comments will be more helpful
thanks!
Instead of using :
Date day = new Date();
Use:
Calendar cal = Calendar.getInstance();
cal.set (...);
Date date = new Date(cal.getTimeInMillis());
Worth abstracting this stuff out to a DateUtils class or similar, with something like the following:
public static Date create(int year, int month, int day, int hour, int minute, int second) {
return new Date(getTimeInMillis(year, month, day, hour, minute, second));
}
public static long getTimeInMillis(int year, int month, int day, int hour, int minute, int second, int milliseconds) {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(year, month, day, hour, minute, second);
cal.set(Calendar.MILLISECOND, milliseconds);
return cal.getTimeInMillis();
}

Automatic correction of Java Calendar day of month?

I want to learn that is there any easiest way to correct the values of day when setting it. I mean:
int birthDay = 30;
int birthMonth = 1;
int birthYear = 1980;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, birthDay);
cal.set(Calendar.MONTH, birthMonth);
cal.set(Calendar.YEAR, birthYear);
February doesn't have the day of 30. On the other hand it has a special condition, 1980 is a year that February is 29 days. So I have to get the corrected value as "1980-February-29". It should take the maximum day of that month if I exceed the range of month. How can I do it at simplest way and if I can find solution that doesn't need to write any extra code instead of using the methods of Calendar class it will be perfect.
EDIT: I changed cal.set(Calendar.MONTH, birthMonth-1); to cal.set(Calendar.MONTH, birthMonth); sorry for it.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, birthYear);
cal.set(Calendar.MONTH, birthMonth);
cal.set(Calendar.DAY_OF_MONTH, Math.min(birthDay, cal.getActualMaximum(Calendar.DAY_OF_MONTH)));
Use calendar.getActualMaximum(Calendar.DAY_OF_MONTH) to find the maximum day of the month
No, currently it's the only way.
Of course, you might want to parse a date from a String using a java.text.DateFormat object (typically a SimpleDateFormat). This is the most close to a one-liner you can get if your input is a String.

Categories