如何检查时间戳是否延迟

时间:2015-09-24 01:25:49

标签: java timestamp

我有时间戳,我想检查时间是在某个时间之前还是之后(上午9:00)。更具体地说,我想知道一个人是否迟到,截止时间是上午9点。我该如何编码?

2015-09-22 08:59:59 //Print on time
2015-09-22 09:00:00 //Print on time
2015-09-22 09:00:01 //Print you are late

4 个答案:

答案 0 :(得分:1)

您可以使用类似于以下内容的代码

window.onload

答案 1 :(得分:1)

我认为你可以这样做:

public static final String TIME_STAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static void main(String[] args) {

        Date standard = getStandardDate();
        SimpleDateFormat format = new SimpleDateFormat(TIME_STAMP_FORMAT);

        List<String> data = new ArrayList<String>();
        data.add("2015-09-22 08:59:59");
        data.add("2015-09-22 09:00:00");
        data.add("2015-09-22 09:00:01");

        for (String date : data) {
            if(isLate(date, format)) {
                System.out.println(date + " is Late");
            } else {
                System.out.println(date + " is On Time");
            }
        }

    }

    /**
     * check is Late or not
     * */
    public static boolean isLate(String date, SimpleDateFormat format) {
        Date standard = getStandardDate();
        Date inputDate = null;
        boolean result = false;
        try {
            inputDate = format.parse(date);
            if(inputDate.after(standard)) {
                result = true;
            } 
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * get standard date
     * */
    public static Date getStandardDate() {
        Date dateNow = new Date ();
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateNow);
        cal.set(Calendar.DAY_OF_MONTH, 22);
        cal.set(Calendar.HOUR_OF_DAY, 9);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
    }

希望这有帮助!

答案 2 :(得分:0)

假设输入为String,您可以执行以下操作

String input = ...;
String time = input.split(" ")[1],
    hour = time.split(":")[0],
    minute = time.split(":")[1],
    seconds = time.split(":")[2];

if(Integer.parseInt(hour) > 9 && Integer.parseInt(minute) > 0) {
    // Not on time
} 

这假设输入总是完美的,你应该使用try-catch块或预先检查输入,因为这可能会抛出异常。

答案 3 :(得分:0)

LocalDateTime time = LocalDateTime.of(2015, 9, 22, 9, 0, 0);
LocalDateTime now = LocalDateTime.now();

if (now.compareTo(time) > 0)
    System.out.println("You are late");
else System.out.println("You are in time");

如果你正在处理字符串,你必须先拆分它们,如@Deximus

所述