欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-08 09:33:30
...
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);  
    }  
  
}  
}   

相关标签: 时间格式

推荐阅读