0

假设我有两个小时之间的差异

java.text.DateFormat f = new java.text.SimpleDateFormat("HH:mm");
java.util.Date checkIn = f.parse("00:00");
java.util.Date checkOut = f.parse("05:00");

Long timeDifference = new Long(checkOut.getTime() - checkIn.getTime());

通过将“timeDifference”除以 3600000(以毫秒为单位的一小时),我可以看到这个间隔有多少小时,我得到了正确的结果,5。

但是当我尝试像这样转换“timeDifference”时:

Calendar cal = new GregorianCalendar();
cal.setTime(new Date(timeDifference));
DateFormat formatter = new SimpleDateFormat("HH:mm");
formatter.format(cal.getTime());

我得到“02:00”......为什么?如何格式化“timeDifference”?

编辑:我真的不在乎日期。我只想要像 HH:mm 这样的小时格式的 checkIn 和 checkOut 之间的区别。

4

4 回答 4

1

尝试这个:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss");
Date zeroDt = new Date(0);
System.out.println(format.format(zero));

你得到:

1970-01-01.02:00:00

这个日期(1970 年 1 月 1 日,02:00)是轴的开始。

现在尝试:

java.text.DateFormat f = new java.text.SimpleDateFormat("HH:mm");
Date checkIn = f.parse("00:00");
Date checkOut = f.parse("05:00");
System.out.println(checkIn.getTime());
System.out.println(checkOut.getTime());

你得到:

-7200000
10800000

如您所见,checkIn 为负数(-2 小时)。这就是为什么 checkOut.getTime() - checkIn.getTime() 给出 5 小时 - (-2 小时) = 7 小时。

您必须记住,对于 1970-01-01.02:00:00 之前的日期,date.getTime() 是负数。

于 2013-05-13T13:23:11.620 回答
0

I get "02:00"... Why? How can I format "timeDifference"?

You are somewhat mis-using these classes. My guess is you are in a Moscow time zone which was GMT+3 in 1970.

The simple answer is to use JoaTime which handles dates like this or just write your own parser and formatters which would be about the same amount of code.

于 2013-05-13T13:06:20.247 回答
0

cal.setTime(new Date(timeDifference)): What you're doing here is setting the time to timeDifference (18000000) milliseconds after Jan 1, 1970 GMT. (If you were to change your SimpleDateFormat to show the date as well as the time, this would be apparent). You're getting 02:00 because that's what time it was in your time zone 18000000 milliseconds after midnight (GMT) on Jan 1, 1970. When I run your code (in California), it gives me 21:00, because we are 4 hours behind you.

It seems as though you're misunderstanding how the Calendar class works - see the documentation here. Beyond that, your question doesn't make it clear what exactly you are trying to accomplish. Hopefully with a better understanding of Calendar you'll be able to figure this out yourself - if not, edit your question and tell us exactly what Date you need.

于 2013-05-13T13:06:34.207 回答
0

这里的基本问题是时差不是日期/时间戳。它不代表“时间点”。接口......以及实现它的DateFormat类用于格式化代表时间点的事物。

我得到“02:00”......为什么?

使用 DataFormat 解析和解析时间值时得到的是“今天”的日期值。发生的情况如下:

  1. "00:00" -> 在本地时区中被解析为今天的午夜 == 自纪元以来的 t1 毫秒。

  2. "05:00" -> 被解析为当地时间今天凌晨 5 点 = 自纪元以来的 t2 毫秒。

  3. t2 - t1 -> 5 小时(以毫秒为单位)

  4. 日期(t2 - t1)-> 纪元后 5 小时

  5. (纪元后 5 小时)作为本地时区的值是“1970-01-01T02:00:00”

  6. 现在扔掉除了小时和分钟之外的所有东西。

如何格式化“timeDifference”?

简单的方法是使用long算术将时间差转换为整数小时和分钟,然后使用String.format(...)或使用固定宽度字段和零填充进行格式化。

于 2013-05-13T13:15:54.207 回答