SimpleDateFormat adds 7 hours?

I am trying to do simple subtraction of dates and getting odd results. For some reason, when I format it with SimpleDateFormat, the 7 hours difference is bigger.

package timedemo;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Timedemo {

    public static void main(String[] args) {
        Date start = new Date(); // time right now
        Date stop = new Date();

        long startTime = start.getTime()-1000; // introduce a second of skew
        long stopTime = stop.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

        // First one shows up prior to 1970 epoch. Okay, except for 5 hour variance.
        // Probably a timezone thing, as I'm in EST (-5).
        System.out.println("New date is "+new Date(stopTime - startTime)); 
        System.out.println("Raw Start is "+startTime); // fine
        System.out.println("Raw Stop is  "+stopTime); // fine
        System.out.println("Raw Difference is "+(stopTime-startTime));
        System.out.println("Formatted Start is "+sdf.format(startTime));
        System.out.println("Formatted Stop is  "+sdf.format(stopTime));
        System.out.println("Formatted Difference is "+sdf.format(stopTime-startTime));

    }

}

      

And the results:

New date is Wed Dec 31 19:00:01 EST 1969
Raw Start is 1418397344360
Raw Stop is  1418397345360
Raw Difference is 1000
Formatted Start is 10:15:44
Formatted Stop is  10:15:45
Formatted Difference is 07:00:01

      

  • I thought it was an hourly topic, but I'm in EST (-5), not MST (-7).
  • I would suspect Daylight Savings, but it's 7 hours, not 1.
  • 12/24 hour difference? 12-7 = 5 which is my temporal offset ... not sure what to do with it though.
  • View from ideas at the moment.

Why is the seven o'clock shift on the last line?

+3


source to share


1 answer


"12-7 = 5" is definitely related to the problem ... or more precisely, "12-5 = 7", i.e. 5 hours before midnight - 7 pm. You will see that if you format it as a full date / time:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

      



Heck, you can see that on your first line, "Wed Dec 31 19:00:01 EST 1969" is 19:00 - 7:00 pm, which you format with hh

like 07

.

Basically, the problem is that you are trying to treat the time difference as if it were a moment in time. I urge you very strongly not to do this. If you absolutely want this (and the difference will always be non-negative, but less than 24 hours), you should set the timezone to SimpleDateFormat

UTC and use hh

instead hh

. But it would be better to use Joda Time or java.time

from Java 8 which can represent Duration

i.e. Difference between two points at time. Date

is not a suitable data type for this.

+8


source







All Articles