how to get near time for the present time [Android Studio]

android get current time
how to add date in android studio
android studio time
android get time of day
android get real time
how to set date and time in android studio
android time format
how to get current timestamp in android

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 result will be:

NEXT TIME : 12:1 PM


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:

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

String inputString = "00:01:30.500";

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

Changing the Time Zone on an Android, How can I get current date and time in Android? Get current time and date on Android Android Mobile Development Apps/Applications As per Oracle documentation, SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.


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:

public static String findNext(String current, String... times) throws ParseException {
    SimpleDateFormat fmt = new SimpleDateFormat("hh:mm a");
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    long currentMillis = fmt.parse(current).getTime();
    long bestMillis = 0, minMillis = 0;
    String bestTime = null, minTime = null;
    for (String time : times) {
        long millis = 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:

public static String findNext(String current, String... times) {
    SimpleDateFormat fmt = new SimpleDateFormat("hh:mm a");
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    int idx = Arrays.binarySearch(times, current, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            try {
                return fmt.parse(s1).compareTo(fmt.parse(s2));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    });
    if (idx < 0)
        idx = -idx - 1;
    return times[idx < times.length ? idx : 0];
}

java, How do I get 24 hour time on my Android? This example demonstrates about how do I get date and time from internet in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project


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

it will works for you surely.

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

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

    public static void main(String argv[])
    {
        new TimeDiff();
    }
    int  nextTimeArrayIndex(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;
          }


    }
    long convertToSec(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.

Date, How do I set the time on my Android phone? Some of android application app developer or application user needs to know about the current date and time setting up in android mobile phone device. So my in this tutorial i am getting the current device date and time and setting them on TextView on button click. So here is the complete step by step tutorial for Get current date and time in


Time, 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  I want to get time and date separately from timestamp.Please help me in these. My example of timestamp is 1378798459. Thanks


LocalTime, Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. As of JDK version 1.1, replaced by Calendar.get(​Calendar. int, the time-zone offset, in minutes, for the current time zone. Developer guides · Design guides · API reference · Samples · Android Studio. Android Platform. API level 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1. Manifest.permission. Manifest.permission_group. android.accessibilityservice. AccessibilityService.MagnificationController.OnMagnificationChangedListener. AccessibilityService.SoftKeyboardController.OnShowModeChangedListener.


Duration, A thin wrapper around the java.util. method is deprecated and should not be used because SQL TIME values do not have a date component. What is best method to measure execution time of Android code snippet? I have a section of code before and after which I want to place timestamps to find out it's execution time (e.g. one in onCreate() and another in onDestroy() method of activity). I have tried Time.toMillies(false), but it only returns seconds to me (with constant 000 at