Skip to content Skip to sidebar Skip to footer

How To Get Near Time For The Present Time [android Studio]

i have 5 times example: 4:21 AM 12:1 PM 3:32 PM 6:30 PM 8:4 PM and the current time is 10:4 AM I want to do a comparison What is the next time closest to the current time the resul

Solution 1:

You can turn a time to a date object and then into a long (milliseconds since Jan 1, 1970), and calculate the difference in milliseconds

long diffInMs = currentDate.getTime() - anotherDate.getTime();

And then check which has the smallest difference, but being also equal to or greater than zero. Negative difference means old date and you want the next closest date

To convert the times to dates check this: https://stackoverflow.com/a/8826392/2597775

Basically, it says:

SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

StringinputString="00:01:30.500";

Datedate= sdf.parse("1970-01-01 " + inputString);

Solution 2:

Update: Added logic to rollover at midnight, and added alternative using binary search.

First parse the inputs to a time in milliseconds of the day, by parsing the time string as if it's in UTC time zone.

Then find the smallest value on or after the "current" value, or just smallest value if no value is on or after the "current" value (rollover).

Example:

publicstatic String findNext(String current, String... times)throws ParseException {
    SimpleDateFormatfmt=newSimpleDateFormat("hh:mm a");
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    longcurrentMillis= fmt.parse(current).getTime();
    longbestMillis=0, minMillis = 0;
    StringbestTime=null, minTime = null;
    for (String time : times) {
        longmillis= fmt.parse(time).getTime();
        if (millis >= currentMillis && (bestTime == null || millis < bestMillis)) {
            bestMillis = millis;
            bestTime = time;
        }
        if (minTime == null || millis < minMillis) {
            minMillis = millis;
            minTime = time;
        }
    }
    return (bestTime != null ? bestTime : minTime);
}

Test

System.out.println(findNext("10:4 AM",
                            "4:21 AM", "12:1 PM", "3:32 PM", "6:30 PM", "8:4 PM"));
System.out.println(findNext("10:4 PM",
                            "4:21 AM", "12:1 PM", "3:32 PM", "6:30 PM", "8:4 PM"));

Output

12:1 PM
4:21 AM

If the given times are guaranteed to already be sorted, then it can be done with a binary search:

publicstaticStringfindNext(String current, String... times) {
    SimpleDateFormat fmt = newSimpleDateFormat("hh:mm a");
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    int idx = Arrays.binarySearch(times, current, newComparator<String>() {
        @Overridepublic int compare(String s1, String s2) {
            try {
                return fmt.parse(s1).compareTo(fmt.parse(s2));
            } catch (ParseException e) {
                thrownewRuntimeException(e);
            }
        }
    });
    if (idx < 0)
        idx = -idx - 1;
    return times[idx < times.length ? idx : 0];
}

Solution 3:

i specially design a function to solve your problem , use function as you needed.

it will works for you surely.

/**
 *
 * @author Niravdas
 */publicclassTimeDiff {
    String[] times = { "04:21 AM", "12:01 PM", "03:32 PM", "06:30 PM", "08:04 PM"};
    String findingafter="10:04 AM";

    publicTimeDiff()
    {
        int time=nextTimeArrayIndex(findingafter,times);
        if(time>=0)
            System.out.println("NEXT TIME: "+times[time]);
    }

    publicstaticvoidmain(String argv[])
    {
        new TimeDiff();
    }
    intnextTimeArrayIndex(String Finding,String[] fromArray)
    {
        int shortest=-1,shortestsec=-1;
        long minsecdif=(24*60*60+1),minsec=(24*60*60+1);
        int hr=Integer.parseInt(Finding.substring(0, 2));
        int min=Integer.parseInt(Finding.substring(3, 5));
        long seconds = convertToSec(hr, min, 0, Finding.substring(Finding.length()-2));
        System.out.println("seconds :" + seconds);
          for(int i=0;i<fromArray.length;i++)
          {
              int temphr=Integer.parseInt(fromArray[i].substring(0, 2));
              int tempmin = Integer.parseInt(fromArray[i].substring(3,5));
              long tempsec = convertToSec(temphr, tempmin, 0, fromArray[i].substring(Finding.length()-2));
              System.out.println("Compared to :" + tempsec);
              if((tempsec - seconds) > 0 && minsecdif > (tempsec - seconds))
              {
                  minsecdif = (tempsec - seconds);
                  shortest = i;
              }
              if(minsec > tempsec)
              {
                  minsec = tempsec;
                  shortestsec=i;
              }
          }
          if(shortest >=0)
          {
              return  shortest;
          }
          else
          {
              return  shortestsec;
          }


    }
    longconvertToSec(int hr,int min,int sec,String AMorPM)
    {
        if(hr==12)
        {
               hr=0;
        }
        long secs = (hr*60*60) + (min*60) + (sec*60);
        if(AMorPM.equalsIgnoreCase("PM"))
        {
            secs += (12*60*60);
        }
        return secs;

    }     

}

i hope it will solve your problem.

Post a Comment for "How To Get Near Time For The Present Time [android Studio]"