Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First off, you should probably just learn to use <a href="http://joda-time.sourceforge.net/" rel="nofollow">Joda time</a>.</p> <p>That said, since the times are all zero padded, you can just compare strings lexically.</p> <pre><code>public static boolean inRange(String time, String range) { return time.compareTo(range.substring(0, 5)) &gt;= 0 &amp;&amp; time.compareTo(range.substring(6)) &lt;= 0; } </code></pre> <p>It's good practice to fail fast on malformed inputs.</p> <pre><code>private static final Pattern VALID_TIME = Pattern.compile("[012][0-9]:[0-5][0-9]"); private static final Pattern VALID_RANGE = Pattern.compile("[012][0-9]:[0-5][0-9]-[012][0-9]:[0-5][0-9]"); </code></pre> <p>and then put an assert at the top of <code>inRange</code>:</p> <pre><code>assert VALID_TIME.matcher(time).matches() : time assert VALID_RANGE.matcher(range).matches() : range </code></pre> <p>EDIT:</p> <p>If you really need to represent the current time as a <code>Date</code>, then you should compare it this way:</p> <pre><code> public final class Range { /** Inclusive as minutes since midnight */ public final int start, end; public Range(int start, int end) { assert end &gt;= start; } /** @param time in minutes since midnight */ public boolean contains(int time) { return start &lt;= time &amp;&amp; time &lt;= end; } public static Range valueOf(String s) { assert VALID_RANGE.matcher(s).matches() : s; return new Range(minutesInDay(s.substring(0, 5)), minutesInDay(s.substring(6)); } private static int minutesInDay(String time) { return Integer.valueOf(time.substring(0, 2)) * 60 + Integer.valueOf(time.substring(3)); } } </code></pre> <p>Use <code>Range.valueOf</code> to convert from a <code>String</code>, convert your <code>Date</code> to a number of minutes since midnight in whatever timezone you like using whatever calendar implementation you like, and then use <code>Range.contains</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload