-1

I am trying to write a code that calculates how many time in seconds left till midnight in a specific timezone.

The time zone I am targeting is EDT which is "GMT-04:00".

I found many topics cover time calculation but none of them helped me figure out the trick to calculate seconds left to midnight in a specific time zone.

Can anyone point me in the right direction?

Thanks.

LoveDroid
  • 75
  • 1
  • 10

2 Answers2

0

I believe this is the logic you’re looking for? (Don’t look at the question, just the first answer, referring to Calendar, Locales and TimeZones)

https://stackoverflow.com/a/39757060/1552960

Using Calendar and time zones to calculate the exact time, then simply use that calendar object to find the difference between another set calendar object at midnight :)

long differenceInMillis = midnightCalendarObject.getTimeInMillis() - calendarObject.getTimeInMillis();

long secondsUntilMidnight = TimeUnit.toSeconds(differenceInMillis);

Brandon
  • 1,158
  • 3
  • 12
  • 22
0

java.time

    ZoneId zone = ZoneId.of("America/New_York");
    ZonedDateTime now = ZonedDateTime.now(zone);
    ZonedDateTime midnight = now.toLocalDate().plusDays(1).atStartOfDay(zone);
    long secondsLeftTillMidnight = Duration.between(now, midnight).getSeconds();
    System.out.println("Seconds till midnight: " + secondsLeftTillMidnight
            + ". Time now: " + now + '.');

Output just now:

Seconds till midnight: 34801. Time now: 2018-10-01T14:19:58.651572-04:00[America/New_York].

Question: Can I use java.time on Android?

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

  • In Java 8 and later and on new Android devices (from API level 26, I’m told) the new API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
  • On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161