java判断某时间是否在一个时间段

来源:互联网 发布:上古卷轴ol捏脸数据 编辑:程序博客网 时间:2024/05/19 23:02

import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
* @ClassName: DateTest
* @Description: TODO
* @author z23bin@163.com
* @date 2016年1月22日 上午11:09:55
*
*/
public class DateTest {

/** * @param args */public static void main(String[] args) {    System.out.println(DateTest.isInTime("20:00-01:00", "01:00"));    System.out.println(DateTest.isInTime("20:00-01:00", "00:00"));    System.out.println(DateTest.isInTime("20:00-01:00", "03:00"));    System.out.println();    System.out.println(DateTest.isInTime("20:00-23:00", "03:00"));    System.out.println(DateTest.isInTime("20:00-23:00", "22:00"));    System.out.println(DateTest.isInTime("20:00-23:00", "18:00"));    System.out.println(DateTest.isInTime("20:00-23:00", "20:00"));    System.out.println(DateTest.isInTime("20:00-23:00", "23:00"));}/** * 判断某一时间是否在一个区间内 *  * @param sourceTime *            时间区间,半闭合,如[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);    }}

}

0 0
原创粉丝点击