javadate

Why does SimpleDateFormat.parse().getTime() return an incorrect (negative) value?


I have a time-stamp of type String and I am trying to convert it to a double (and find the result in seconds) and here is what I have done:

double mytimeStamp = 0;

String timeStamp = new SimpleDateFormat(" mm ss S").format(new Date( ));   

SimpleDateFormat dateFormat = new SimpleDateFormat(" mm ss S");

try {
  mytimeStamp = ((double)dateFormat.parse(timeStamp).getTime())/1000;
} catch (ParseException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
}

System.out.println("timeStamp is: "+ mytimeStamp);

The problem is that I obtain a value such as -2722.515 and I don't know why.

Why is it negative?

Is there something wrong with the code?

When I convert this time-stamp to mm ss S does not match with the real time and this seems to be another problem!


Solution

  • It's a time zone discrepancy issue.

    Since you only specified the minute and second, the date will be on 1 Jan 1970 00:mm:ss (mm and ss being the minutes and seconds of the current time).

    I simplified your example to:

    String timeStamp = "00 00 00";
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH mm ss");
    double hour = dateFormat.parse(timeStamp).getTime()/1000.0/60/60;
    System.out.println("hour is: "+ hour);
    

    The hour printed out should be GMT's offset from the local time zone.

    The reason for this is:

    SimpleDateFormat is locale-sensitive, so dateFormat.parse(timeStamp) will return create a Date object for a given time zone (the default is the local time zone). Then getTime() gets the number of milliseconds from midnight 1 Jan 1970 **GMT**. So the value will be offset by how far the local time zone is from GMT.

    How to fix it:

    You could fix it by setting the time zone of the dateFormat object before parse is called as follows:

    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));