两个日期之间的差异 (Android)

Difference between two dates (Android)

我需要获取两个日期之间的时间。假设 dateStart = 1470712122173dateStop = 1470712127320。 这两个日期之间的差等于 5147 因此,据此我希望得到答案 = 5 秒,但我看到 19:00:05。这19个小时从哪里来?

毫秒代码 (=5147) -> 时间:

private string foo(long dateStart, long dateStop) {
    long diff = dateStop - dateStart;
    DateFormat simple = SimpleDateFormat.getTimeInstance(); 
    Date date = new Date(diff); 
    return simple.format(date);
}

感谢您的解释。

您需要掌握正确的基本概念。当您在两个 Date 对象之间取差异时,您会得到两个时间点之间的持续时间,试图将差异视为另一个时间点是没有意义的。

下面是一个使用Java 8 次API 得到两个时间点之间的差异的例子(java.time.Instant):

import java.time.Duration;
import java.time.Instant;

public class TimeDifferenceSample {

    static Duration diff(Instant start, Instant end) {
        return Duration.between(start, end);
    }

    public static void main(String [] args) {
        long start = 1470712122173L;
        long end = 1470712127320L;

        Duration dur = diff(Instant.ofEpochMilli(start), Instant.ofEpochMilli(end));
        System.out.println(dur.getSeconds() + " seconds");
    }
}

输出:

5 seconds

对于Android,我不是专家,但你可以查看The Joda Time Project, which provides similar functions. I also found an Android verion here

    Date date = new Date(5147);
   //this method has deprecation, just for illustration
    System.out.println(date.getSeconds());

 //in java 8 this works
        LocalDateTime ldate1 = LocalDateTime.ofInstant(Instant.ofEpochMilli(1470712122173l), ZoneId.systemDefault());
        LocalDateTime ldate2 = LocalDateTime.ofInstant(Instant.ofEpochMilli(1470712127320l), ZoneId.systemDefault());

        System.out.println(Duration.between(ldate1, ldate2).getSeconds());

您也可以使用java.util.concurrent.TimeUnit

输出

0 : 0 : 5

代码

import java.util.concurrent.TimeUnit;

public class HelloWorld {

    public static void main(String[] args) {
        long dateStart = 1470712122173l, dateStop = 1470712127320l;
        long diff = dateStop - dateStart;

        long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);
        long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(diff);
        long diffInHours = TimeUnit.MILLISECONDS.toHours(diff);

        System.out.println(diffInHours + " : " + diffInMinutes + " : " + diffInSeconds);
    }
}

当您计算两个日期实例之间的差异时,您实际上得到的是秒数差异。假设您得到 30 seconds 作为差异。

现在,如果您将此 30 seconds 再次转换为 date 实例(12 小时内)格式,那么您将得到 12 hr 00 minutes 30 seconds PM 的答案。所以当你计算两个日期之间的差异时,你不应该将差异转换回日期实例。