Search code examples
javaandroidandroid-studiosimpledateformatandroid-timepicker

How to get time entered by user in EditText and deduct 5 hrs 30 minutes from it?


I had two edit text for user to enter time (24 hours format). How could i get those times from Edittext and deduct 5 hours and 30 minutes from user selected time.

Reason for deducting time : Converting IST to UTC timezone.

My final output should be like - HH:MM:SS:Milleseconds (Ex : 18:25:30:245635).

Thanks in advance.


Solution

  • java.time

        ZoneId zone = ZoneId.of("Asia/Kolkata");
        String timeString = "18:25:30.245635";
        LocalTime time = LocalTime.parse(timeString);
        LocalTime utcTime = LocalDate.now(zone)        // Today
                .atTime(time)                          // Today at the time in question
                .atZone(zone)                          // Date and time in IST
                .toOffsetDateTime()                    // Convert to OffsetDateTime for the next step
                .withOffsetSameInstant(ZoneOffset.UTC) // Convert to UTC
                .toLocalTime();                        // Extract only the time of day
        System.out.println("UTC time: " + utcTime);
    

    Output is:

    UTC time: 12:55:30.245635

    I have assumed today’s date. Please check if this assumption is right for you. While the UTC offset for Asia/Kolkata hasn’t changed much recently, other time zones change their offset twice a year.

    I changed your time format to have a period (point) rather than a colon between the seconds and fraction of second as is customary. If you do require a colon there, you need a DateTimeFormatter for parsing.

    Question: Can I use java.time on Android?

    Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

    • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
    • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
    • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

    Links