从日期减去日期偏移量

时间:2013-06-25 18:49:44

标签: java date

当我打印日期时,我可以看到偏移量为-6.00

2012-12-31T18:00:00 -0600

是否有一种干净的方式将偏移量添加到日期,我在java.util.Date中看不到任何内容。

我使用以下内容打印日期:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z");
String date = sdf.format(new Date(dateInMilliseconds));

1 个答案:

答案 0 :(得分:2)

偏移量与TimeZone有关。

如果您正在使用Calendar,则可以像这样获取TimeZone:

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();

如果您有TimeZone实例,则可以获取给定日期的偏移量,如下所示:

int offset = tz.getOffset(cal.getTime().getTime());

当你问“我可以添加偏移吗?”时,我不确定你的意思。

如果您想标准化日期,可以使用UTC时间。

您可以使用SimpleDateFormat这样做:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(new Date()));

现在输出:

  2013-06-25T19:09:10