时间比较 [英] Time comparison

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

问题描述

我有一个时间在 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).

一个选项是使用< =http://joda-time.sourceforge.net/ =nofollow noreferrer> 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天全站免登陆