如何检查时间是否在特定范围之间? [英] How to check whether a time is between particular range?

查看:75
本文介绍了如何检查时间是否在特定范围之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查当前时间是否在8 AM到3 PM之间。如果是在这些时间范围之间,那么我需要返回yes或者返回false。

I need to check whether current time is between 8 AM and 3 PM or not. If it is between those time range, then I need to return yes otherwise return false.

boolean isNowBetweenDateTime(final Date s, final Date e) {
    final Date now = new Date();
    return now.after(s) && now.before(e);
}

但我不知道我应该使用 Date 这里?我可以不使用时间戳并相应地检查时间戳吗?这样做的正确方法是什么?

But I am not sure I should be using Date here? Can I just not use timestamp and check timestamp accordingly? What is the right way to do this?

我还在Java 7上。

I am still on Java 7.

推荐答案

如果您在Java 8之前使用Java版本,请查看 Joda

If you're using a version of Java prior to Java 8, take a look at the API documentation for Joda.

具体来说,有一个 AbstractInterval#containsNow()方法,这将允许你做你想要的。

Specifically, there is an AbstractInterval#containsNow() method which will allow you to do what you want.

例如:

new Interval(start, end).containsNow();

其中start和end可以是多个不同值/对象中的任何一个。请参阅可用的不同构造函数的文档:间隔

where start and end can either be any of a number of different values/objects. See the documentation for the different constructors available: Interval

您可以将您的方法修改为如下所示:

You could modify your method to be like so:

boolean isNowBetweenDateTime(final DateTime s, final DateTime e) {
    return new Interval(s, e).containsNow();
}

也就是说,这只是一行,所以你真的不需要用你自己的方法包装:)

That said, it's only one line, so you really shouldn't need to wrap it with your own method :)

再次看一下文档。 Interval构造函数可以使用各种对象/值,因此可以选择适合您的需求。我推荐DateTime,因为它似乎最好地描述了你想要做什么。

Again, take a look at the documentation. The Interval constructor can take a variety of objects/values, so pick whichever suits your needs. I recommend DateTime since it seems to best describe what you're looking to do.

这篇关于如何检查时间是否在特定范围之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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