Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

java - How to know if now time is between two hours?

I have a now time:

new Date();

And I have some hour constants, for example, 23 and 8 (it's 11pm or 23:00, 8am or 08:00). How I can know is now time between it's two hour constants?

It need to run some code of program or not to run if now time is between in two hours, for example, do not run some code if its already evening and while it is not a morning.

Here the image to better explain:

enter image description here

Some situations when silent mode does not fire:

00:00 20.06.13 - 23:00 20.06.13 // after 23.00 can loud!!

23:00 20.06.13 - 15:00 20.06.13 // after 15.00 can loud!!

01:00 20.06.13 - 08:00 20.06.13 // after 08.00 can loud!!

21:00 20.06.13 - 08:00 20.06.13 // after 08.00 can loud!!
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try this

    int from = 2300;
    int to = 800;
    Date date = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    int t = c.get(Calendar.HOUR_OF_DAY) * 100 + c.get(Calendar.MINUTE);
    boolean isBetween = to > from && t >= from && t <= to || to < from && (t >= from || t <= to);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...