时间减法有什么问题?

What's wrong with time subtraction?

我知道 Date class 有时真的很痛苦。

你能给我一些止痛药吗,比如关于如何减去时间的建议?

我有的是:

SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
String s = "13.04.2015 16:00";
String s2 = "13.04.2015 15:30";
Date date = format.parse(s);
System.out.println(timeFormat.format(date.getTime() - format.parse(s2).getTime()));

这给了我 02:30:00,但我很想得到 00:30:00 :)

我建议对 SimpleDateFormat:

强制使用公共 TimeZone
format.setTimeZone(TimeZone.getTimeZone("UTC"));
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

格式化前 date.

我不确定您是否因为某些要求而坚持 Java 日期 class,但是如果您在应用程序中经常使用日期和时间,我建议 Joda-Time library.它解决了许多开箱即用的问题,并允许以更简单的方式对日期和时间执行操作。