I am receiving a time from my server in UTC ISO8601
format like so:
2018-01-25T05:14:03.4973436
I am converting this string
to milliseconds
and I am generating
a time elapsed value using my current time
like so:
public static CharSequence getRelativeTimeSpan(String timeStamp) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = format.parse(timeStamp);
long past = date.getTime();
int offset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
long now = System.currentTimeMillis() + offset;
return DateUtils.getRelativeTimeSpanString(
past,
now,
DateUtils.MINUTE_IN_MILLIS);
}
However, for some reason, the code produces an immediate difference of 12 hours
between past and now. I'm not sure why there is such a difference but for instance this UTC
string ( 2018-01-25T05:14:03.4973436 )
generates the following milliseconds
value ( 1516857243000 )
which doesn't really correspond to the current time
in milliseconds
.
The interesting part of all of this is that there's this automatic 12 hour
difference. I made sure that I use "HH"
instead of "hh"
to account for AM/PM
differences so I don't know what's causing this discrepancy.
UPDATED USING JAVA8 time - still the same behavior
I have updated the code with the following snippet and I am getting the exact same behavior ( 12 hour immediate difference )
public static CharSequence getRelativeTimeSpan(String timeStamp) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS");
LocalDateTime fromCustomPattern = LocalDateTime.parse(timeStamp, formatter);
return DateUtils.getRelativeTimeSpanString(
fromCustomPattern.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(),
Instant.now().toEpochMilli(),
DateUtils.MINUTE_IN_MILLIS);
}