0

I am trying to adjust the current time to get the previous hour time on the hour boundaryfor eg: if the current time is say 10:45 AM I am trying to get the adjusted time as 10:AM, the below code works for most part, but I tried to run it on a machine in IST (Indian Standard Time ) for some reason it goes back to 10:30AM not 10:00 AM, But when I run in PST,EDT,EST it works fine.

Below is what I tried , can any tell me why this behavior , I am using System.currentTimeMillis so the longs value should be independent of timezone right ?

    long adjustedTime = System.currentTimeMillis();
    long resolution = 3600000L;
    long rem = (int) Math.IEEEremainder( adjustedTime , resolution );
    if ( rem < 0 )
        rem = resolution + rem;
    adjustedTime = adjustedTime - rem ;
    return adjustedTime;
Chandu
  • 1,049
  • 3
  • 11
  • 18

3 Answers3

1

I would use the Calendar class like this

java.util.Calendar cal = java.util.Calendar.getInstance();
int hour = cal.get(java.util.Calendar.HOUR_OF_DAY);

Which should always give you the correct hour of the day.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

I think that you should use % instead of Math.IEEEremainder:

adjustedTime = adjustedTime - (adjustedTime % resolution);
user987339
  • 10,519
  • 8
  • 40
  • 45
  • See also: [Difference in Java, if any, between the % operator and the IEEEremainder() method?](http://stackoverflow.com/a/8012709/687315) – quietmint Dec 26 '13 at 04:05
1

You're calculating based on UTC not local time. This is then converted back to IST which is +5:30 UTC. The other time zones you mentioned are on even hour boundaries with UTC.

Jodatime almost always is a better way to start. Here's a thread on how to get the hour and other information:

Java: getMinutes and getHours

Community
  • 1
  • 1
Tracy Snell
  • 1,278
  • 10
  • 8
  • Tracy, thanks for your response. I think it makes sense, any idea how i can correct this, basically i need to adjust the current time to previous hour on the hour boundary.. – Chandu Dec 26 '13 at 03:54
  • Haven't tested but I think Elliot's solution will work. I added a pointed to another thread that has some good information for you. – Tracy Snell Dec 26 '13 at 03:57
  • +1 for Joda Time. To get the start of the current hour, simply use `DateTime.now().withMinuteOfHour(0)` – quietmint Dec 26 '13 at 04:08