java - JodaTime - Check if LocalTime is after now and now before another LocalTime -
i trying check if currenttime after startlocaltime , before endlocaltime start time plus 11 hours. works fine if start time 11:00 (end time 22:00). when try compare start time of 16:00 , end time of 03:00, currenttime.isbefore(endtime) never logged, should be.
localtime currenttime = localtime.now(); //21:14 localtime starttime = new localtime( 16, 00, 0, 0); localtime endtime = starttime.plushours(11); //03:00 midnight if(currenttime.isafter(starttime)){ log.v("test", "after starttime"); } if(currenttime.isbefore(endtime)){ log.v("test", "before endtime"); } any ideas how solve problem?
basically need check whether starttime , endtime inverted (i.e. if endtime before starttime). if is, must "night-time" interval, , should treat if other way round, , invert result.
public boolean iswithininterval(localtime start, localtime end, localtime time) { if (start.isafter(end)) { return !iswithininterval(end, start, time); } // assumes want inclusive start , exclusive end point. return start.compareto(time) <= 0 && time.compareto(end) < 0; } now oddity here shown, start time inclusive , end time exclusive - whereas if invert result (and arguments) have inclusive end time , exclusive start time. might want handle cases explicitly instead:
public boolean iswithininterval(localtime start, localtime end, localtime time) { if (start.isafter(end)) { // return true if time after (or at) start, *or* it's before end return time.compareto(start) >= 0 || time.compareto(end) < 0; } else { return start.compareto(time) <= 0 && time.compareto(end) < 0; } } (how choose target , argument use compareto you, of course. there multiple ways of writing same code.)
short complete example:
import org.joda.time.localtime; public class test { public static void main(string[] args) { localtime morning = new localtime(6, 0, 0); localtime evening = new localtime(18, 0, 0); localtime noon = new localtime(12, 0, 0); localtime midnight = new localtime(0, 0, 0); system.out.println(iswithininterval(morning, evening, noon)); // true system.out.println( iswithininterval(morning, evening, midnight)); // false system.out.println( iswithininterval(evening, morning, noon)); // false system.out.println( iswithininterval(evening, morning, midnight)); // true } public static boolean iswithininterval(localtime start, localtime end, localtime time) { if (start.isafter(end)) { // return true if time after (or at) start, // *or* it's before end return time.compareto(start) >= 0 || time.compareto(end) < 0; } else { return start.compareto(time) <= 0 && time.compareto(end) < 0; } } }
Comments
Post a Comment