I am comparing a date object with two date objects. I want to know that the object lies within the range. So here is my code to compare: I will get three date objects, one belongs to my current time, other two belongs to before and after time.
public String calcOpenClosed(String timeRange, Date currentTime)
{
Log.e("current time got", currentTime.getHours()+" "+currentTime.getMinutes());
if(timeRange.contains(","))
{
String[] slot = timeRange.split(",");
String[] range1 = slot[0].split("-");
String[] range2 = slot[1].split("-");
Date date1;
Date date2;
Date date3;
Date date4;
Log.e("range 1", range1[0]);
Log.e("range 2", range1[1]);
Log.e("range 3", range2[0]);
Log.e("range 4", range2[1]);
date1 = getTime(range1[0]);
date2 = getTime(range1[1]);
date3 = getTime(range2[0]);
date4 = getTime(range2[1]);
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
Calendar cal3 = Calendar.getInstance();
Calendar cal4 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
cal3.setTime(date3);
cal4.setTime(date4);
Calendar curr = Calendar.getInstance();
curr.setTime(currentTime);
if(curr.after(cal1) && curr.before(cal2) || curr.after(cal3) && curr.after(cal4))
{
return "OPEN NOW";
}
else
{
return "CLOSED";
}
}
else
{
String[] range = timeRange.split("-");
Date date1;
Date date2;
date1 = getTime(range[0]);
date2 = getTime(range[1]);
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
Calendar curr = Calendar.getInstance();
curr.setTime(currentTime);
if(curr.after(cal1) || curr.before(cal2))
{
return "OPEN NOW";
}
else
{
return "CLOSED";
}
}
}
public Date getTime(String timeCreated) {
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH)+1;
int year = calendar.get(Calendar.YEAR);
String date = year + "-" +(month<10?("0"+month):(month)) +"-"+day;
String timeCreatedSlot[] = timeCreated.split(" ");
String[] splittedTime = timeCreatedSlot[0].split(":");
int time = Integer.parseInt(splittedTime[0]);
String timeNow = String.valueOf(time<10?("0"+time):(time));
String finalTime = date + " "+ timeNow + ":" + splittedTime[1]+ " "+timeCreatedSlot[1];
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm aaa");
try {
Date timeCreatedDate = dateFormat.parse(finalTime);
Log.e("time created", timeCreatedDate.getHours()+"");
return timeCreatedDate;
} catch (ParseException e) {
Log.e("exception", "setTimestamp: " + Log.getStackTraceString(e));
}
return null;
}
Its working fine but its giving me wrong result when the time range is 4:00 AM - 00:00 AM. The above code I have tried with date.before and date.after also. But giving same result.