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

前端 未结 2 445
你的背包
你的背包 2020-12-18 00:26

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 mytimeStam         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 01:04

    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"));
    

提交回复
热议问题