We help IT Professionals succeed at work.

Java - Running a statement during specific periods of time

Mike Miller
Mike Miller asked
on
I'm trying to create an if/then statement in which the contents can only be run if it is executed during a specific time period.

I want to set a variable to a specific time, and another variable to a number (which will be minutes)

If the system time is in between the variable time and the number of minutes, then do nothing. Else, do something.

For example...
If my variable time is 23:45 and my minuted is 15, the "then" would not occur if executed between 23:45 and 24:00.

TIA
Comment
Watch Question

Top Expert 2016

Commented:
Use the Calendar class to create your start and end times. e.g.
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
Date start = c.getTime().getTime();
c.add(Calendar.MINUTE, minutesDelta);
Date end = c.getTime().getTime();
Date now = new Date();
if(now.after(start) && now.before(end)) {
   // Do it
}

Open in new window

Mike MillerSoftware Engineer

Author

Commented:
Type mismatch converting long to date on start and end with the below code
Calendar c = Calendar.getInstance();
		int hour = Integer.parseInt(getConfigProperty("StopProcessHour", false));
		int minute = Integer.parseInt(getConfigProperty("StopProcessMin", false));
		c.set(Calendar.HOUR_OF_DAY, hour);
		c.set(Calendar.MINUTE, minute);
		Date start = c.getTime().getTime();
		int minutesDelta;
		c.add(Calendar.MINUTE, minutesDelta);
		Date end = c.getTime().getTime();
		Date now = new Date();
		if(now.after(start) && now.before(end)) {
		   // Do it
		}

Open in new window

Top Expert 2016

Commented:
You didn't initialize 'minutesDelta'...
Mike MillerSoftware Engineer

Author

Commented:
Same error with this...
Calendar c = Calendar.getInstance();
		int hour = Integer.parseInt(getConfigProperty("StopProcessHour", false));
		int minute = Integer.parseInt(getConfigProperty("StopProcessMin", false));
		c.set(Calendar.HOUR_OF_DAY, hour);
		c.set(Calendar.MINUTE, minute);
		Date start = c.getTime().getTime();
		int minutesDelta = Integer.parseInt(getConfigProperty("SpecificMinutes", false));
		c.add(Calendar.MINUTE, minutesDelta);
		Date end = c.getTime().getTime();
		Date now = new Date();
		if(now.after(start) && now.before(end)) {
		   // Do it
		}

Open in new window

Top Expert 2016

Commented:
Can you please post your exact error message? What happens when you temporarily hard-code the int values?
Top Expert 2016
Commented:
So sorry -

>>Date start = c.getTime().getTime();

should have been
Date start = c.getTime();

Open in new window

Mike MillerSoftware Engineer

Author

Commented:
That worked! Thanks
Top Expert 2016

Commented:
:)