Reputation: 4973
I started looking at joda API for handling timezone related issues for my web application. I found very weird behavior while doing so. I hope there must be some workaround. here is my snap-code.
DateTime utcDateTime = new DateTime(System.currentTimeMillis(), DateTimeZone.UTC);
DateTime currentDateTime = DateTime.now();
int seconds = Seconds.secondsBetween(utcDateTime.toLocalDateTime(), currentDateTime.toLocalDateTime()).getSeconds();
System.out.println("hours::" + (((float)seconds)/(60*60)));
My local timezone is : kolkata, India (GMT + 5:30)
then I should get 5.5 as myn console output, but I am getting hours::5.499722
Don't know Why? Am I doing anything wrong?
Upvotes: 0
Views: 70
Reputation: 39403
(5.5 hours - 5.499722 hours) in ms
=
1000.8 ms
1 second, to the rounding/floating point precision. You call
DateTime utcDateTime = new DateTime(System.currentTimeMillis(), DateTimeZone.UTC);
DateTime currentDateTime = DateTime.now();
Seconds.secondsBetween().getSeconds()
gives you an integer number of seconds. Your calls are successive meaning they can be off by even 1 millisecond, which can be rounded to 1 second when converted to int.
Upvotes: 1
Reputation: 1503839
Given that you want hours and minutes (an Hours
object can only hold an integer number of hours) you probably want:
Period period = new Period(utcDateTime.toLocalDateTime(),
currentDateTime.toLocalDateTime(),
PeriodType.time());
Or alternatively, and more cleanly IMO:
int offsetMillis = DateTimeZone.getDefault().getOffset(Instant.now());
Duration offset = Duration.millis(offsetMillis);
You should very rarely need to know the offset in this fashion though, in my experience.
Upvotes: 1