SimpleDateFormat fails to format Date interval?

我只是一个虾纸丫 提交于 2020-01-04 13:46:13

问题


I try to format a time interval using SimpleDateFormat.

import java.text.*;
import java.util.*;

public class DateFormatTest {
  public static void main(String[] args) {
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
    long interval = 1000;
    System.out.println("Interval in millis: " + interval);
    System.out.println("Expected result: 00:00:01");
    System.out.println("Result using Date and SimpleDateFormat: " +
      sdf.format(new Date(interval)));
  }
}

I get the following result:

Interval in millis: 1000
Expected result: 00:00:01
Result using Date and SimpleDateFormat: 01:00:01

I am in GMT+1 time zone. But it should not be reflected in the result.

Of course it can be solved with System.out.printf, but what I am searching is the reason.


回答1:


I am in GMT+1 time zone. But it should not be reflected in the result.

Then you should set the time zone in the SimpleDateFormat. SimpleDateFormat is doing exactly the right thing - it's formatting the instant in time (just after midnight UTC 1970) in the time zone it's working in.

To change the time zone, just use:

sdf.setTimeZone(TimeZone.getTimeZone("etc/UTC"));

It's not clear whether you should really be using SimpleDateFormat at all, though. You're not trying to format a date/time - you're trying to format an interval, given your variable name.

I suggest you use Joda Time which has a much richer type system, and will allow you to express what you really want.

Also, if you really want to use SimpleDateFormat, you probably want to use HH instead of hh in your format string. (hh is a 12-hour value, 1-12. You want 00:00:01, not 12:00:01.) hh is rarely appropriate when you don't also have an am/pm designator in your pattern.




回答2:


I am in GMT+1 time zone. But should not be reflected in the result.

What makes you think so? new Date(0) is at 00:00AM GMT on Jan 1st 1970. So it is at 01:00AM if your default timezone is GMT + 1.



来源:https://stackoverflow.com/questions/14171568/simpledateformat-fails-to-format-date-interval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!