如何计算 java(jsp) 之前的时间

How to calculate Time ago in in java(jsp)

朋友 我是 java 中新使用的日期和时间。 我将日期和时间存储在当前时间的字符串中,同样我还有一个字符串变量,它具有 post 时间 现在我想计算之前的时间,甚至以秒为单位 该字符串具有这种格式的日期和时间 yyyy/MM/dd HH:mm:ss 有人能帮我吗 谢谢 这是代码

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

        LocalDateTime currentTime = LocalDateTime.parse(d_tt, formatter);
        LocalDateTime postTime = LocalDateTime.parse(post_time, formatter);

        long seconds = ChronoUnit.SECONDS.between(postTime, currentTime);//(error here)

错误“ChronoUnit 不能 已解决

对于这种情况最好使用LocalDateTime

首先你必须将这两个字符串转换成 LocalDateTime

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

LocalDateTime currentTime = LocalDateTime.parse(currentTimeString, formatter); // Or use LocalDateTime.now()
LocalDateTime postTime = LocalDateTime.parse(postTimeString, formatter);

然后可以使用这些对象来确定它们之间的时间。有两种可能性可以做到这一点。它们都给出相同的结果,您可以根据自己的喜好使用它来确定它们之间的时间。

可能性一:

long seconds = postTime.until(currentTime, ChronoUnit.SECONDS);

可能性一:

long seconds = ChronoUnit.SECONDS.between(postTime, currentTime);

您还可以在这里获取更多信息:

  1. Introduction to the Java 8 Date/Time API
  2. Java 8: Difference between two LocalDateTime in multiple units