java.time
I strongly recommend that you use java.time, the modern Java date and time API, for your time work.
private static final ZoneId ZONE = ZoneId.of("America/Vancouver");
private static final double MINUTES_PER_DAY = Duration.ofDays(1).toMinutes();
public static double getDayTimeDouble(String timestamp){
timestamp = "2020-12-20T09:12:41Z";
ZonedDateTime zdt = Instant.parse(timestamp)
.atZone(ZONE);
double result = zdt.get(ChronoField.MINUTE_OF_DAY) / MINUTES_PER_DAY;
return result;
}
Since the time of day in Pacific Canada is 01:12:41 Pacific Standard Time (-08:00) at this time, the method returns
0.05
Please substitute your desired time zone if it differs.
As the code stands, it doesn’t take the seconds into the calculation. You may want to use a similar approach using ChronoField.SEOND_OF_DAY
or one of the other XXX_OF_DAY
fields. See the link below for available fields.
What went wrong in your code?
While I wasn’t able to get any exception from your method, there are some problems with is:
- You were trying to use
Date
and SimpleDateformat
. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. You shuold avoid them.
- Worse yet, you were using
Date.getHours()
and Date.getMinutes()
. These methods have been deprecated since Java 1.1 (February 1997) because they work unreliably across time zones.
- Your parsing is incorrect. The
Z
, pronounced Zulu, in the string means UTC or an offset of zero from UTC. When you are hardcoding it as a literal, you are missing this important information and most probably getting an incorrect result.
- Apparently you didn’t take time zone into account. It is never the same time of day in all time zones, so you need to decide on a time zone for you calculation. I recommend that you make this explicit in your code so the next person reading it also can understand what goes on. Use
ZoneId.systemDefault()
if you want and dare to rely on the JVM’s current time zone setting.
- You were performing an integer division. The result of
(date.getHours() * 60 + date.getMinutes())
is an int
, and the result of (24 * 60)
is an int
too. The former is always less than the latter. So your division gives an int
result and always 0. Then Java implicitly converts this 0 to a double
, so you get 0.0 each time.
Links