如何转换时间戳以获得 Android 中的精确毫秒差异?

How to convert time stamp to get exact milliseconds difference in Android?

我有这种格式的时间: 如果我有像 Y1 = 05:41:54.771Y2 = 05:42:03.465 这样的时间,我希望得到精确的毫秒差值。对于上面的示例,精确的毫秒差异将是“6693 毫秒”。我该如何实现?


            Date date = new Date(timestamp);
  DateFormat format = new SimpleDateFormat("hh:mm:ss.SSS",Locale.getDefault());
       
    
} 
    



您提供的代码行是一个 DateFormat 对象,它接受日期并将其格式化为字符串表示形式。它没有存储任何实际数据。您想对实际日期对象进行比较,而不是格式化程序。

有几种不同的时间存储方式,但存储时间戳的常用方式是 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;

或者,有处理结构化时间数据的库和工具可能有其他存储时间戳和比较它们的方法,但是如果您只需要快速比较两个时间戳,这是一个常见的简单实现的快速示例.

你的方向是正确的。使用 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);
}

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 and

使用现代日期时间 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

关于此解决方案的一些重要说明:

  1. 没有日期,SimpleDateFormat 解析日期为 January 1, 1970 GMT 的时间字符串。
  2. Date#getTime returns 自 1970 年 1 月 1 日以来的毫秒数,00:00:00 GMT 由此 Date 对象表示。
  3. 使用 H 而不是 h 作为 24-Hour 格式的时间值。