How to check if date is between interval in java? -
this question has answer here:
- creating java date object year,month,day 6 answers
i have 6 int
variables: currentmonth
, currentday
, monthfrom
, dayfrom
, monthuntil
, dayuntil
. need check if todays month , day falls within range of , until variables.
for example if currentmonth = 1
, currentday = 2
, monthfrom = 11
, dayfrom = 24
, monthuntil = 3
, dayuntil = 3
date in interval , method should return true.
i'm not sure how though. there other option check every possible outcome using ifs?
just quick range check calendar:
note: make sure import java.util.gregoriancalendar;
public static boolean isdateinrange(int month, int day, int monthfrom, int dayfrom, int monthuntil, int dayuntil) { int yearroll = 0; int currentroll = 0; if (monthuntil < monthfrom) yearroll = -1; // ensures date calculated correctly. if (month >= monthfrom && yearroll < 0) currentroll = -1; gregoriancalendar testdate = new gregoriancalendar(currentroll, month, day); gregoriancalendar startdate = new gregoriancalendar(yearroll, monthfrom, dayfrom); gregoriancalendar enddate = new gregoriancalendar(0, monthuntil, dayuntil); // makes pass if between or equal interval. // remove if want pass dates explicitly between intervals. if (testdate.compareto(startdate) == 0 || testdate.compareto(enddate) == 0) { return true; } return !(testdate.before(startdate) || testdate.after(enddate)); }
this take account fact february between november , march. since november part of previous year, move from
date year ensure passing.
what doesn't take account however, fact february has day on leap-years. add extra-precision, need integers years. can following:
public static boolean isdateinrange(int year, int month, int day, int yearfrom, int monthfrom, int dayfrom, int yearuntil, int monthuntil, int dayuntil) { gregoriancalendar testdate = new gregoriancalendar(year, month, day); gregoriancalendar startdate = new gregoriancalendar(yearfrom, monthfrom, dayfrom); gregoriancalendar enddate = new gregoriancalendar(yearuntil, monthuntil, dayuntil); return !(testdate.before(startdate) || testdate.after(enddate)); }
and here implementation date values gave plus few more:
public static void main(string[] args) { system.out.println(isdateinrange(1, 2, 11, 24, 3, 3)); system.out.println(isdateinrange(11, 25, 11, 24, 3, 3)); system.out.println(isdateinrange(1, 2, 1, 1, 3, 3)); system.out.println(isdateinrange(1, 22, 1, 21, 1, 25)); }
and results are:
true true true true
will work @marvin's tests.
Comments
Post a Comment