0

I have a variable Date someDate = new Date(0) that starts at the Unix Epoch and is incremented. I need to test whether the time of someDate is currently between 0000 and 1200 hours. Essentially I need to be able to compare a Date object with a time range.

Is there a way to do this in Java, or do I need to roll my own or use something like Joda-Time?

3
  • what is wrong with long? Commented Nov 19, 2013 at 23:51
  • How do you increment someDate? Commented Nov 20, 2013 at 0:00
  • This is for a simulation, so someDate is not incremented in real time. A timer waits a set interval and then adds some other number of seconds to someDate. Commented Nov 20, 2013 at 0:04

2 Answers 2

1

You can use a Calendar. See this:

Calendar c = Calendar.getInstance(); c.setTime(someDate); int hour = c.get(Calendar.HOUR_OF_DAY); if (hour < 12) { // 0 <= hour < 12 } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Not as elegant as I was hoping for, but easier than dragging in another library.
0

You could actually use Joda time, but if you just want to compare dates, you could just use the compareTo method from the Date java class, javadoc here

1 Comment

I don't want to compare dates, only the time of day.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.