Link to home
Start Free TrialLog in
Avatar of Member_2_1242703
Member_2_1242703

asked on

Java - Running a statement during specific periods of time

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
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

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

Avatar of Member_2_1242703
Member_2_1242703

ASKER

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

You didn't initialize 'minutesDelta'...
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

Can you please post your exact error message? What happens when you temporarily hard-code the int values?
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That worked! Thanks
:)