如何比较两个不同的时间戳并找到最新的

how to compare two different timestamp and find the latest

我有两个不同的时间戳值作为字符串。我需要找到哪个是最新的。其格式为 [YYYYMMDDHHMMSS]

时间戳是:

20150804030251
20150804040544

有什么简单的方法可以使用 Java 8 获取最新的吗?

是的,这些时间戳的格式很容易比较。

if ( Long.parseLong(timesteamp1) < Long.parseLong(timestamp2) ) {
  //timestamp2 is later than timestamp1
}

这是可能的,因为最重要的部分,年份,在整数的最重要部分,最左边;其余部分从左到右按重要性递减顺序排列;每个部分使用固定数量的数字,例如 02 月而不是 2 月。否则这种简单的方法是不可能的。

您也可以按字典顺序比较它们。在这种格式的特定情况下,前面的代码等效于:

if ( timestamp1.compareTo(timestamp2) < 0 ) {
  // timestamp2 is later than timestamp 1
}

您仍然可以试试这个。在这里不使用 Java 8

中的任何特殊功能
String timeStamp1 = "20150804030251";
String timeStamp2 = "20150804040544";
DateFormat dateFormat = new SimpleDateFormat("yyyyMMhhHHmmss");
Date date1 = dateFormat.parse(timeStamp1);
Date date2 = dateFormat.parse(timeStamp2);
if(date1.after(date2)){
  System.out.println("latest "+date1);
}else {
  System.out.println("latest "+date2);
}

您可以在 java 8 中创建本地日期对象,如下所示

LocalDateTime dt = LocalDateTime.parse("20150804030251",
                DateTimeFormatter.ofPattern("YYYYMMDDHHMMSS")

LocalDateTime dt2 = LocalDateTime.parse("20150804030251",
                DateTimeFormatter.ofPattern("YYYYMMDDHHMMSS")

然后使用dt.isBefore(dt2)

进行比较

您甚至不必解析这些字符串。只需使用 compareTo():

"20150804030251".compareTo("20150804040544");

More info

不幸的是,现有答案中的 none 是正确的。先跟他们讨论一下问题:

  • 的工作纯属巧合。它恰好起作用只是因为这些值是按时间单位(年、月、日、小时、分钟、秒)的递减顺序排列的。如果他们的位置发生变化,它将失败,例如MMyyyy...。这种方法的另一个严重问题是它无法验证错误的值,例如15 位数字而不是 14 位数字。
  • 与接受的答案有类似的问题。它比较的不是数值,而是 ASCII 值,因此可能会因与接受的答案中提到的相同原因而失败。
  • is the idiomatic way of doing it, but it is wrong because it uses Y (which specifies week-based-year) instead of y (which specifies year-of-era) and D (which specifies day-of-year) instead of d (which specifies day-of-month). In fact, it is to use u instead of y. Check the documentation 页 了解有关这些符号的更多信息。
  • is blatantly wrong. Date(long date) 应该用编号初始化对象。自 1970-01-01T00:00:00Z.
  • 以来的毫秒数

至此,您一定已经想出了解决方案,为了完整起见,我在下面发布了解决方案:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String strDateTime1 = "20150804030251";
        String strDateTime2 = "20150804040544";

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");

        LocalDateTime ldt1 = LocalDateTime.parse(strDateTime1, dtf);
        LocalDateTime ldt2 = LocalDateTime.parse(strDateTime2, dtf);

        LocalDateTime latest = ldt1.isAfter(ldt2) ? ldt1 : ldt2;

        System.out.println(latest);
    }
}

输出:

2015-08-04T04:05:44

详细了解 modern date-time API* from Trail: Date Time


* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and