java.time
If you want to convert the time of day to milliseconds:
ZoneId zone = ZoneId.of("Europe/Rome");
LocalTime timeOfDay = LocalTime.now(zone);
long milliOfDay = TimeUnit.NANOSECONDS.toMillis(timeOfDay.toNanoOfDay());
System.out.println(milliOfDay);
If instead I am to take it literally when you asked for number of milliseconds since the start of the day:
ZonedDateTime now = ZonedDateTime.now(zone);
ZonedDateTime startOfDay = now.toLocalDate().atStartOfDay(zone);
Duration dur = Duration.between(startOfDay, now);
long millisSinceStartOfDay = dur.toMillis();
System.out.println(millisSinceStartOfDay);
When I ran the two snippets just now (15:18:28 in Italy), they both printed
55108833
Is there any difference, then? In by far the most cases, the two snippets above will print the same result. However, if for example there is a transition to or from summer time (daylight saving time) earlier the same day, the local time will not reflect the time passed since the start of day, and then the snippets will give different results. So you should choose carefully which one of them you want.
Since the number of milliseconds since midnight will never overflow an int
, you can safely cast to that type if you prefer.
Rather than the long outdated and poorly designed Calendar
class I am using java.time
, the modern Java date and time API. It is so much nicer to work with.
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, I’m told) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new 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