您的位置:首页 > 其它

判断输入的时间格式和判断当前输入的时间是否在输入的时间范围内

2017-09-08 10:43 429 查看
package com.itcast.demo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;

public class DateTest {

/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String st1=sc.nextLine();
String st2=sc.nextLine();
if(isInTime(st1,st2)){
System.out.println("当前时间在时间范围内");
}else{
System.out.println("当前时间不在时间范围内");
}
}

public static boolean isValidDate(String str) {
boolean convertSuccess=true;
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
try {
format.setLenient(false);
format.parse(str);
} catch (ParseException e) {

convertSuccess=false;
}
return convertSuccess;
}

/**
* 判断某一时间是否在一个区间内
*
* @param sourceTime
*            时间区间,半闭合,如[10:00-20:00)
* @param curTime
*            需要判断的时间 如10:00
* @return
* @return
* @throws IllegalArgumentException
*/
public static  boolean isInTime(String sourceTime, String curTime) {
if (sourceTime != null || sourceTime.contains("-") || sourceTime.contains(":")) {
String[] args = sourceTime.split("-");
for(int i=0; i<args.length; i++){
if(!isValidDate(args[i])){
throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
}
}

}else{
throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
}
if (curTime != null || curTime.contains(":")) {
if(!isValidDate(curTime)){
throw new IllegalArgumentException("Illegal Argument arg:" + curTime);
}
} else{
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);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: