0

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.

Khushal Chouhan
  • 581
  • 5
  • 15
  • 4
    When you stepped through your code with a debugger for the input time range of 4:00-00:00, what did you find that didn't behave the way it should? Why? What confuses you about that behavior? – Sotirios Delimanolis Aug 24 '16 at 17:34
  • When I am having current time 23:00 and time range is 4 PM to 12AM, its giving me wrong response, its should give me true whereas its giving me false. – Khushal Chouhan Aug 24 '16 at 19:22
  • which line gives the unexpected result? – bradimus Aug 24 '16 at 19:44
  • 00:00 AM if the same month, day, and year is earlier than 04:00 AM. So unless the month, day, and year of the "00:00" is after that of the "04:00", you will have an empty range. Unfortunately you have not provided enough information in our question to know if that's what is going on. Please clarify. – Lew Bloch Aug 24 '16 at 21:10
  • 1
    Way too much code. Try to strip it down to the bare essentials when posting to StackOverflow. We are here to solve specific programming problems, not review your code. [See MCVE](http://stackoverflow.com/help/mcve). – Basil Bourque Aug 24 '16 at 22:37

1 Answers1

0

First, separate your String handling from the date-time code. Get the Strings parsed into date-time objects, then hand-off those objects to a separate logic method. And you’ll make your life easier if you avoid a heavy reliance on strings and instead pass around objects.

Secondly, you are using troublesome old legacy date-time classes now supplanted by the java.time classes.

If you are trying to focus on opening-closing times as generic time-of-day values rather than specific date-time moments, use the LocalTime class.

LocalTime openingTime = LocalTime.parse ( "04:00" );
LocalTime closingTime = LocalTime.parse ( "00:00" );
Boolean inRange = null;
LocalTime target = LocalTime.MIDNIGHT; // LocalTime.of ( 3 , 0) or LocalTime.of ( 4 , 0) or LocalTime.of ( 5 , 0) or LocalTime.now ( ZoneId.of ( "America/Los_Angeles" ) );
if ( closingTime.equals ( LocalTime.MIDNIGHT ) ) {
    inRange = (  ! target.isBefore ( openingTime ) );
} else {
    inRange = ( (  ! target.isBefore ( openingTime ) ) && ( target.isBefore ( closingTime ) ) );
}

Or you can write that logic on a single line. Personally I would stick with the if-else construct.

Boolean inRange2 = ( (  ! target.isBefore ( openingTime ) ) && ( closingTime.equals ( LocalTime.MIDNIGHT ) ? true : target.isBefore ( closingTime ) ) );

Dump to console.

System.out.println ( "openingTime: " + openingTime + " | closingTime: " + closingTime + " | target: " + target + " | inRange: " + inRange + " | inRange2: " + inRange2 );

In real-world work I would verify inputs by checking for the closing time being after the opening (or equal to LocalTime.MIDNIGHT as the only exception).

Half-Open

The code above takes the Half-Open approach to interpreting a span of time as the beginning being inclusive while the ending is exclusive. This is sensible common practice in date-time work.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154