如何在 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());
       
    
} 
    



解决方法

java.util 的日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到 modern date-time API

使用现代日期时间 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 返回自 1970 年 1 月 1 日格林威治标准时间 00:00:00 以来由该 Date 对象表示的毫秒数。
  3. 使用 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;

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