时间对比 [英] Time comparison

查看:23
本文介绍了时间对比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 hh:mm 中有一个时间,它必须由用户以该格式输入.

I have a time in hh:mm and it has to be entered by the user in that format.

但是,我想比较一下时间(例如 11:22)是在上午 10 点到下午 6 点之间吗?但我如何比较呢?

However, I want to compare the time (eg. 11:22) is it between 10am to 6pm? But how do I compare it?

推荐答案

Java(还)没有一个很好的内置 Time 类(它有一个用于 JDBC 查询,但那不是你想要什么).

Java doesn't (yet) have a good built-in Time class (it has one for JDBC queries, but that's not what you want).

一种选择是使用 JodaTime API 及其 LocalTime 类.

One option would be use the JodaTime APIs and its LocalTime class.

只使用内置的 Java API,您就会陷入 java.util.Date.您可以使用 SimpleDateFormat 来解析时间,然后 Date 比较函数以查看它是在其他时间之前还是之后:

Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date comparison functions to see if it is before or after some other time:

SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");

try {
    Date userDate = parser.parse(someOtherDate);
    if (userDate.after(ten) && userDate.before(eighteen)) {
        ...
    }
} catch (ParseException e) {
    // Invalid date was entered
}

或者你可以只使用一些字符串操作,也许是一个正则表达式来提取小时和分钟部分,将它们转换为数字并进行数字比较:

Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:

Pattern p = Pattern.compile("(d{2}):(d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
    String hourString = m.group(1);
    String minuteString = m.group(2);
    int hour = Integer.parseInt(hourString);
    int minute = Integer.parseInt(minuteString);

    if (hour >= 10 && hour <= 18) {
        ...
    }
}

这完全取决于您要完成的任务.

It really all depends on what you are trying to accomplish.

这篇关于时间对比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆