用于限時循環(huán)的活動:
public class TestDate
{
public static void main(String[] args)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String strDate = sdf.format(date);
// 截取當前時間時分
int strDateH = Integer.parseInt(strDate.substring(11, 13));
int strDateM = Integer.parseInt(strDate.substring(14, 16));
String curTime = strDateH+":"+strDateM;
System.out.println(curTime);
String sourceTime ="09:00-23:00";
boolean inTime = isInTime(sourceTime, curTime);
System.out.println(inTime);
}
/**
* 判斷某一時間是否在一個區(qū)間內(nèi)
*
* @param sourceTime
* 時間區(qū)間,半閉合,如[10:00-20:00)
* @param curTime
* 需要判斷的時間 如10:00
* @return
* @throws IllegalArgumentException
*/
public static boolean isInTime(String sourceTime, String curTime) {
if (sourceTime == null || !sourceTime.contains("-") || !sourceTime.contains(":")) {
throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
}
if (curTime == null || !curTime.contains(":")) {
throw new IllegalArgumentException("Illegal Argument arg:" + curTime);
}
String[] args = sourceTime.split("-");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
try {
long now = sdf.parse(curTime).getTime();
long start = sdf.parse(args[0]).getTime();
long end = sdf.parse(args[1]).getTime();
if (args[1].equals("00:00")) {
args[1] = "24:00";
}
if (end < start) {
if (now >= end && now < start) {
return false;
} else {
return true;
}
}
else {
if (now >= start && now < end) {
return true;
} else {
return false;
}
}
} catch (ParseException e) {
e.printStackTrace();
throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
}
}
}