问题描述
我有时间采用这种格式:
如果我有 Y1 = 05:41:54.771
和 Y2 = 05:42:03.465
之类的时间,我希望有以毫秒为单位的精确差异。对于上面的示例,精确的毫秒差异将是“6693 毫秒”。我如何实现这一目标?
Date date = new Date(timestamp);
DateFormat format = new SimpleDateFormat("hh:mm:ss.SSS",Locale.getDefault());
}
解决方法
java.util
的日期时间 API 及其格式化 API SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到 modern date-time API。
- 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7。
- 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。
使用现代日期时间 API:
import java.time.Duration;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
long millisBetween = Duration.between(LocalTime.parse("05:41:54.771"),LocalTime.parse("05:42:03.465"))
.toMillis();
System.out.println(millisBetween);
}
}
输出:
8694
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
使用旧 API:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS",Locale.ENGLISH);
long millisBetween = sdf.parse("05:42:03.465").getTime() - sdf.parse("05:41:54.771").getTime();
System.out.println(millisBetween);
}
}
输出:
8694
有关此解决方案的一些重要说明:
- 没有日期,
SimpleDateFormat
解析日期为January 1,1970 GMT
的时间字符串。 -
Date#getTime
返回自 1970 年 1 月 1 日格林威治标准时间 00:00:00 以来由该Date
对象表示的毫秒数。 - 使用
H
而不是h
作为24-Hour
格式的时间值。
您的方向是正确的。使用 DateFormat 的 parse()
方法,您可以获得一个 Date
对象。然后将其转换为即时并获得自纪元以来的毫秒数。最后是一个简单的减法。
DateFormat format = new SimpleDateFormat("hh:mm:ss.SSS",Locale.getDefault());
try {
Instant y1 = format.parse("05:41:54.771").toInstant();
Instant y2 = format.parse("05:42:03.465").toInstant();
long diffMillis = y2.toEpochMilli() - y1.toEpochMilli();
System.out.println(diffMillis);
} catch (ParseException e) {
throw new RuntimeException(e);
}
,
您提供的代码行是一个 DateFormat
对象,它接受一个日期并将其格式化为字符串表示形式。它没有存储任何实际数据。您想对实际日期对象进行比较,而不是格式化程序。
有几种不同的方式来存储时间,但一种常见的方式来存储时间戳是作为 Long
。由于 long 是数字,您可以像 Int
一样进行比较和数学运算:
Long startTime = System.currentTimeMillis();
// Do some long task here that we want to know the duration of
Long endTime = System.currentTimeMillis();
Long difference = endTime - startTime;
或者,有一些用于处理结构化时间数据的库和工具可能有其他存储时间戳和比较它们的方式,但是如果您只需要快速比较两个时间戳,这是一个常见的简单实现的快速示例。