I'm trying to create a method which is checking if "today" is between Monday and Friday. For this I get with this line 'int day = Calendar.DAY_OF_WEEK;' the actual day. After that I fill a ArrayList with the days (Monday, Tuesday, Wendsday, Thursday and Friday). Now when I check if the actual day is in my ArrayList, i set boolean DAY = true else i set boolean DAY = false. I tryed the Method today and yesterday, but it allways sets the boolean to false.
What do I need to change that my code works? You'll find the code down here.
Code
int day = Calendar.DAY_OF_WEEK;
ArrayList<Integer> daylist = new ArrayList<Integer>();
daylist.add(Calendar.MONDAY);
daylist.add(Calendar.TUESDAY);
daylist.add(Calendar.WEDNESDAY);
daylist.add(Calendar.THURSDAY);
daylist.add(Calendar.FRIDAY);
if (daylist.contains(day)){
DAY = true;
}else{
DAY = false;
}
Wow, that's like trying to kill a mosquito with a thermo-nuclear warhead :-)
Java guarantees (in 1.5) (unchanged up to 1.8 at least) that the values of SUNDAY through SATURDAY are contiguous (1 through 7) so it's a simple matter of checking a range.
However, DAY_OF_WEEK is not the day of the week, it's a field number (with the value 7) to be passed to the getter to retrieve the day of the week. The only time Calendar.DAY_OF_WEEK itself will match an actual day will be on Saturdays.
You can use code such as:
Calendar myDate = Calendar.getInstance(); // set this up however you need it.
int dow = myDate.get (Calendar.DAY_OF_WEEK);
boolean isWeekday = ((dow >= Calendar.MONDAY) && (dow <= Calendar.FRIDAY));
Following this, isWeekday will be true if and only if the day from myDate was Monday through Friday inclusive.
int day = Calendar.DAY_OF_WEEK; should instead be
Calendar cal; // The calendar object
....your other code for getting the date goes here....
int day = cal.get(Calendar.DAY_OF_WEEK);
Your current code just gets the value of the constant Calendar.DAY_OF_WEEK.
This should do the trick for you i assume.
int day = cal.get(Calendar.DAY_OF_WEEK);
if (day >= Calendar.MONDAY && day <= Calendar.FRIDAY){
DAY = true;
}else{
DAY = false;
}
int day = Calendar.DAY_OF_WEEK;
The logic is broken right here. DAY_OF_WEEK is a constant identifying which type of data we need to retrieve from a Calendar instance.
The simplest solution to your problem (since Calendar.FRIDAY > ... > Calendar.MONDAY) is
Calendar now = Calendar.getInstance();
int day = now.get(Calendar.DAY_OF_WEEK);
if (day >= Calendar.MONDAY && day <= Calendar.FRIDAY)
// do something
First Calendar.DAY_OF_WEEK is an integer field will always gives you 7. You need to create an instance of a Calendar like Calendar cal = Calendar.getInstance(); By default it gives you the current date in current timezone.
Then you can call cal.get(Calendar.DAY_OF_WEEK); which will give you any day between Sunday and Sat'day
Now you can check something like this
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
System.out.println("Weekend");
} else {
System.out.println("Weekday");
}
You can apply this logic to your problem!!
Related
I have the following method that I took from the accepted answer this question Calculate number of weekdays between two dates in Java
public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
int workDays = 0;
//Return 0 if start and end are the same
if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
return 0;
}
if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
startCal.setTime(endDate);
endCal.setTime(startDate);
}
do {
//excluding start date
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
} while (startCal.getTimeInMillis() < endCal.getTimeInMillis()); //excluding end date
return workDays;
}
I pass to that function the first day and the last day of the current month I get the days like this:
Calendar firstDayOfMonth = Calendar.getInstance();
firstDayOfMonth .set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
Calendar lastDayOfMonth = Calendar.getInstance();
lastDayOfMonth .set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
and I pass the parameters to the function like this:
getWorkingDaysBetweenTwoDates(firstDayOfMonth.getTime(),
lastDayOfMonth.getTime());
I try the method and is returning 21 and we are in November of 2016 and this month have 22 working days not 21
I printed in console the parameters and these are the paramaters that I'm passing to the method
firstDayOfMonth.getTime() //equals to this Tue Nov 01 09:09:47 VET 2016
lastDayOfMonth.getTime() //equals to this Wed Nov 30 09:09:47 VET 2016
Indeed, to have the correct number :
do {
// excluding start date
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
}
should be replaced by :
do {
// excluding start date
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
startCal.add(Calendar.DAY_OF_MONTH, 1);
}
But I see another problem.
To give a correct result, the function supposes that there is a little time difference between the two date parameters :
For example, if you provide two dates (01-11-2016 and 30-11-2016) with last part of the datetime to 00:00:00:00, the days number returned will be 21.
If you create one date, after the second date, you will get 22.
The problem happens here :
while (startCal.getTimeInMillis() < endCal.getTimeInMillis());
Because even if it has only some milliseconds between startCal and endCal in the last iteration, it adds one undesirable day in the result.
To have a deterministic result, you should consider only day (and not time) in the transmitted dates :
Calendar firstDayOfMonth = Calendar.getInstance();
firstDayOfMonth.set(Calendar.MILLISECOND, 0);
firstDayOfMonth.set(Calendar.SECOND, 0);
firstDayOfMonth.set(Calendar.MINUTE, 0);
firstDayOfMonth.set(Calendar.HOUR, 0);
firstDayOfMonth.set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
Calendar lastDayOfMonth = Calendar.getInstance();
lastDayOfMonth.set(Calendar.MILLISECOND, 0);
lastDayOfMonth.set(Calendar.SECOND, 0);
lastDayOfMonth.set(Calendar.MINUTE, 0);
lastDayOfMonth.set(Calendar.HOUR, 0);
lastDayOfMonth.set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
int nbDays = getWorkingDaysBetweenTwoDates(firstDayOfMonth.getTime(),
lastDayOfMonth.getTime());
and use this condition in the loop :
while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());
This condition seems more natural since if the actual date is not after the last date (so before or equals), it should increment the counter for one additional day. Why exclude the last day ?
With Java 8 or JodaTime, it would be more simple and clean to set date values.
To avoid this kind of problem, I think that the getWorkingDaysBetweenTwoDates() method should reset to zero the time part of date parameters or use more specificDate objects (LocalDate for example) as parameters.
Replace startCal.getTimeInMillis() < endCal.getTimeInMillis()) with startCal.getTimeInMillis() <= endCal.getTimeInMillis()).
You current code act like end date not included in range.
How to find out if the today date is the first day of the current month.
Say, today is 24/05/2015 but it is not first day of the month.
what is the best way to get the output.
Extract the "day" part and compare it to 1:
if (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
System.out.println ("Today is the first day of the month");
}
Check if it is say 1 of the month, like so:
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
if (day == 1) {
// first day of the month.
}
Using joda:
boolean isFirstDay = new DateTime(dateObject).getDayOfMonth() == 1;
if(isFirstDay) {
// do whatever
} else {
// whatever
}
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):
In my app I´m saving when I last updated some data from my server.
Therefore I used:
long time = Calendar.getInstance().getTimeInMillis();
Now I want that the data is updated twice a year at 03.03 and 08.08.
How can I check wheater one of these two date boarders were crossed since last update?
Change them to time in mseconds and compare:
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 3);
long time2= c.getTimeInMillis();
c.set(Calendar.MONTH, Calendar.AUGUST);
c.set(Calendar.DAY_OF_MONTH, 8);
long time3= c.getTimeInMillis();
if(time>time2){
//Logic
if(time>time3){
//Logic
}
}
There is something very important which took me a while to figure it out and can be very helpful to people out there, if you are looking for an answer to any of the following questions this is for you:
Why is my date not showing correctly?
Why even when I set the time manually it is not showing right?
Why is the month and the year showing one day less than the one that I set?
For some reason Java sorts the months values like an array, what I mean is that for Java January is 0 and DECEMBER is 11. Same happens for the year, if you set December as month 12 and year as 2012, and then try to do a "system.out.println" of the month and the year, it will show my month as January and the year as 2013!!
so what should you do?
Calendar cal = new GregorianCalendar();
cal.set(2012, 11, 26); // the date I want to input is 26/12/2012 (for Java, 11 is December!)
NOW WHAT IS THE CORRECT WAY TO GET THAT DATE TO SEE IT ON THE SCREEN?
if you try to "system.out.println of yourCalendar.DATE, yourCalendar.MONTH and yourCalendar.YEAR," THAT WILL NOT SHOW YOU THE RIGHT DATE!!!!
If you want to display the dates you need to do the following:
System.out.println (calact.get (calact.DATE));
// displays day
System.out.println (calact.get (calact.MONTH)+1);
//add 1 remember it saves values from 0-11
System.out.println (calact.get (calact.YEAR));
// displays year
NOW IF YOU ARE HANDLING STRINGS THAT REPRESENT DATES, OR....
IF YOU NEED TO COMPARE DATES BETWEEN RANGES , LET'S SAY YOU NEED TO KNOW IF DATE "A" WILL TAKE PLACE WITHIN THE NEXT 10 DAYS....THIS....IS.....FOR....YOU!!
In my case I was working with a string that had format "15/07/2012", I needed to know if that date would take place within the next 10 days, therefore I had to do the following:
1 get that string date and transform it into a calendar ( StringTokenizer was used here )
this is very simple
StringTokenizer tokens=new StringTokenizer(myDateAsString, "/");
do nextToken and before returning the day, parse it as integer and return it.
Remember for month before returning substract 1.
I will post the code for the first you create the other two:
public int getMeD(String fecha){
int miDia = 0;
String tmd = "0";
StringTokenizer tokens=new StringTokenizer(fecha, "/");
tmd = tokens.nextToken();
miDia = Integer.parseInt(tmd);
return miDia;
}
2 THEN YOU CREATE THE CALENDAR
Calendar cal = new GregorianCalendar(); // calendar
String myDateAsString= "15/07/2012"; // my Date As String
int MYcald = getMeD(myDateAsString); // returns integer
int MYcalm = getMeM(myDateAsString); // returns integer
int MYcaly = getMeY(myDateAsString); // returns integer
cal.set(MYcaly, MYcalm, MYcald);
3 get my current date (TODAY)
Calendar curr = new GregorianCalendar(); // current cal
calact.setTimeInMillis(System.currentTimeMillis());
4 create temporal calendar to go into the future 10 days
Calendar caltemp = new GregorianCalendar(); // temp cal
caltemp.setTimeInMillis(System.currentTimeMillis());
caltemp.add(calact.DAY_OF_MONTH, 10); // we move into the future
5 compare among all 3 calendars
here basically you ask if the date that I was given is for sure taking place in the future AND (&&) IF the given date is also less than the future date which had 10 days more, then please show me "EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!" OTHERWISE SHOW ME:
"EVENT WILL NOT TAKE PLACE WITHIN THE NEXT 10 DAYS".
if((cal.getTimeInMillis() > curr.getTimeInMillis()) && (cal.getTimeInMillis()< curr.getTimeInMillis()))
{ System.out.println ("EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!");}
else
{ System.out.println ("EVENT WILL *NOT* TAKE PLACE WITHIN THE NEXT 10 DAYS");}
ALRIGHT GUYS AND GIRLS I HOPE THAT HELPS. A BIG HUG FOR YOU ALL AND GOOD LUCK WITH YOUR PROJECTS!
PEACE.
YOAV.
If the comparison should involve only the year, month and day then you can use this method for check if c1 is before c2. Ugly, but works.
public static boolean before(Calendar c1, Calendar c2){
int c1Year = c1.get(Calendar.YEAR);
int c1Month = c1.get(Calendar.MONTH);
int c1Day = c1.get(Calendar.DAY_OF_MONTH);
int c2Year = c2.get(Calendar.YEAR);
int c2Month = c2.get(Calendar.MONTH);
int c2Day = c2.get(Calendar.DAY_OF_MONTH);
if(c1Year<c2Year){
return true;
}else if (c1Year>c2Year){
return false;
}else{
if(c1Month>c2Month){
return false;
}else if(c1Month<c2Month){
return true;
}else{
return c1Day<c2Day;
}
}
}
used compareTo method ..and this returns integer value .if returns -ve the days before in current date else return +ve the days after come current date
I have an application that passes in java.util.Date. I want to check whether this date is within a specified time of day (e.g. between 10:30 & 11:30), I don't care about the date, just the time of day.
Can anyone show me a simple way to do this?
Thanks
This is what the Calendar class is for. Assuming date is your Date object:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
if (hour == 10 && minutes >= 30 || hour == 11 && minutes <= 30) {
...
}