如何比较 Java 中的两个 utc 时间戳?
How to compare two utc timestamps in Java?
我正在使用以下方法生成 UTC 时间戳,并想将其与另一个进行比较。为此,我正在使用 Apache Commons Lang 库。
如何比较两个时间戳并确定哪个更大?
String msgPushedTimestamp = 2016-05-11T19:50:17.141Z
String logFileTimestamp = 2016-05-11T14:52:02.970Z
这就是我使用 Apache Commons Lang 库生成时间戳的方式。
String msgPushedTimestamp = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("UTC")).format(System.currentTimeMillis());
让 class 实现 Comparable 接口,您可以使用核心 Java 的 compareTo 方法。适用于 String 类型的时间戳,因为这是您的情况。
您可以将它们作为字符串进行比较,因为您的日期格式 (ISO 8601) 在字典顺序上是可比较的。
int compare = msgPushedTimestamp.compareTo(logFileTimestamp);
if (compare < 0) {
// msgPushedTimestamp is earlier
} else if (compare > 0) {
// logFileTimestamp is earlier
} else {
// they are equal
}
我正在使用以下方法生成 UTC 时间戳,并想将其与另一个进行比较。为此,我正在使用 Apache Commons Lang 库。
如何比较两个时间戳并确定哪个更大?
String msgPushedTimestamp = 2016-05-11T19:50:17.141Z
String logFileTimestamp = 2016-05-11T14:52:02.970Z
这就是我使用 Apache Commons Lang 库生成时间戳的方式。
String msgPushedTimestamp = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("UTC")).format(System.currentTimeMillis());
让 class 实现 Comparable 接口,您可以使用核心 Java 的 compareTo 方法。适用于 String 类型的时间戳,因为这是您的情况。
您可以将它们作为字符串进行比较,因为您的日期格式 (ISO 8601) 在字典顺序上是可比较的。
int compare = msgPushedTimestamp.compareTo(logFileTimestamp);
if (compare < 0) {
// msgPushedTimestamp is earlier
} else if (compare > 0) {
// logFileTimestamp is earlier
} else {
// they are equal
}