Thursday 15 March 2012

android - Java Check if a given hour and minute lies between two dates' hours and minutes -



android - Java Check if a given hour and minute lies between two dates' hours and minutes -

i have time spans:

long datestart = system.currenttimemillis(); long dateend = system.currenttimemillis() + 60*60*1000;

i want check if mhour , mminute lies between datestart , dateend.

for example, mhour = 11 , mminute = 22, want is, datestart < 11:22 < dateend

here date not matter.

another example:

2014/10/25 15:46 < 10:30 < 2014/10/26 : 15:45, expected result true. because, 2014/10/26 10:30 < 2014/10/26 : 15:45

a clarification:

the lower , upper bounds of datestart , dateend cannot exceed 1 day span. so, if datestart 2014/10/26 23:59, dateend 2014/10/27 23:58.

i have done did not work out:

comparetime(datestart ,dateend ,mhour ,mminute ); public static void comparetime(long time1, long time2, int mhour, int mminute) throws parseexception { calendar calendar1 = calendar.getinstance(); calendar1.settime(new date(time2)); calendar calendar2 = calendar.getinstance(); calendar2.settime(new date(time1)); calendar2.add(calendar.date, 1); string somerandomtime = selectedhour + ":" + selectedminute; date d = new simpledateformat("hh:mm").parse(somerandomtime); calendar calendar3 = calendar.getinstance(); calendar3.settime(d); calendar3.add(calendar.date, 1); date x = calendar3.gettime(); if (x.after(calendar1.gettime()) && x.before(calendar2.gettime())) system.out.println(true); }

it's joda-time library. comparetime method looks like:

/** * @param time1 datefrom in millis. e.g. returned system.currenttimemillis() * @param time2 dateto in millis * @param mhour hours in time zone * @param mminute minutes in time zone */ public static boolean comparetime(long time1, long time2, int mhour, int mminute) { final localtime timefrom = new localtime(time1); final localtime timeto = new localtime(time2); final localtime time = new localtime(mhour, mminute); final boolean issameday = timefrom.isbefore(timeto); // correct, because (time2 - time1 < 24 hours) homecoming issameday ? (time.isafter(timefrom) && time.isbefore(timeto)) : (time.isafter(timefrom) || time.isbefore(timeto)); }

java android jodatime

No comments:

Post a Comment