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

用于限时循环的活动:

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);

}

/**

* 判断某一时间是否在一个区间内

*

* @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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值