このJava関数は、現在の時刻が他の2つの時刻の間にある場合にtrueを返します。年/月/日は無視されます。
import java.text.*;
import java.util.Date;
public static boolean isNowBetweenHours() throws ParseException
{
String leftBoundaryHours = "01:00:00"; //01:00 hours, military time.(1AM)
String rightBoundaryHours = "14:00:00"; //14:00 hours, military time.(2PM)
//returns true if current time is between
//leftBoundaryHours and rightBoundaryHours.
//This formatter converts a bare string to a date.
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
//add the hand specified time to 1970-01-01 to create left/right boundaries.
Date leftTimeBoundary = formatter.parse("1970-01-01 " + leftBoundaryHours);
Date rightTimeBoundary = formatter.parse("1970-01-01 " + rightBoundaryHours);
//extract only the hours, minutes and seconds from the current Date.
DateFormat extract_time_formatter = new SimpleDateFormat("HH:mm:ss");
//Get the current time, put that into a string, add the 1970-01-01,
Date now = formatter.parse("1970-01-01 " +
extract_time_formatter.format(new Date()));
//So it is easy now, with the year, month and day forced as 1970-01-01
//all you do is make sure now is after left, and now is before right.
if (now.after(leftTimeBoundary) && now.before(rightTimeBoundary))
return true;
else
return false;
}
次のような関数を呼び出します。
try {
System.out.println(isNowBetweenHours());
} catch (ParseException e) {
}
現在の時刻が01:00
数時間後、前14:00 hours
の場合、trueを返します。それ以外の場合はfalseを返します。