一种简单实现当前时间是否在工作时间内的方法

  在工作中,碰到要判断是否在工作时间内的逻辑,而配置的工作起始、结束时间格式是时分秒。实现思想是将其转换为1970年1月1日那天的时间,然后进行比较。

package com.oom.study.util;

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

public class Test {

  private static final String STYLE_TIME = "HH:mm:ss";
  
  private static final String START_TIME = "09:00:00";
  private static final String END_TIME = "21:00:00";
  
  public static void main(String[] args) throws ParseException {
    
    Date startTime = new SimpleDateFormat(STYLE_TIME).parse(START_TIME);
    Date endTime = new SimpleDateFormat(STYLE_TIME).parse(END_TIME);
    Date tempCurrentTime = new Date();
    String currentTimeStr = new SimpleDateFormat(STYLE_TIME).format(tempCurrentTime);
    Date currentTime = new SimpleDateFormat(STYLE_TIME).parse(currentTimeStr);
    if(!(currentTime.after(startTime) && currentTime.before(endTime))) {
        System.out.println("不好意思,当前不在工作时间内");
    }else {
        System.out.println("您好,很高兴为您服务!");
    }
  }
}

  如当前是20:58:00,运行结果是:您好,很高兴为您服务!

  如当前是21:05:01,运行结果是:不好意思,当前不在工作时间内

  Debug运行如下所示:

猜你喜欢

转载自www.cnblogs.com/wangjinxiang/p/10764942.html