如果当前时间介于另外两个时间之间,则此 java 函数返回 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。