如何通过比较两个 Java 时间戳找到以毫秒为单位的经过时间

huangapple go评论83阅读模式
英文:

How to find elapsed time in milliseconds by compare two timestamps in java

问题

我需要通过比较Java中的当前时间戳和创建时间戳来找到以毫秒为单位的经过时间。

例如:

数据库列中的更新时间戳:20年7月26日 12:00:19.330000000 PM
当前时间戳:20年7月26日 11:55:19.330000000 AM

配置的超时时间为2分钟。

为了获取当前时间戳,

  public static Timestamp getTimestampinGMT(Date date) {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      df.setTimeZone(TimeZone.getTimeZone("GMT"));
      String strCurrentTimeInGMT = df.format(date);
      return Timestamp.valueOf(strCurrentTimeInGMT);
  }

我正在将来自数据库的更新时间戳列转换为毫秒

Timestamp.valueOf(createtime).getTime()

配置的2分钟超时时间转换为毫秒,

TimeUnit.MINUTES.toMillis(2);

有没有更好的方法来比较时间戳并计算经过的时间?

英文:

I need to find elapsed time in milliseconds by comparing current time in timestamp with created timestamp in java

For example

Updated Timestamp from DB column : 26/07/20 12:00:19.330000000 PM
Current Timestamp : 26/07/20 11:55:19.330000000 AM

Timeout configured 2 mins

To get current timestamp,

  public static Timestamp getTimestampinGMT(Date date) {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      df.setTimeZone(TimeZone.getTimeZone("GMT"));
      String strCurrentTimeInGMT = df.format(date);
      return Timestamp.valueOf(strCurrentTimeInGMT);
  }

And I'm converting updated timestamp column from DB to millisecond

Timestamp.valueOf(createtime).getTime()

Timeout configured 2 mins is converted to millsec,

TimeUnit.MINUTES.toMillis(2);

Is there any best way to compare timestamp and calculate the elapsed time?

答案1

得分: 1

从数据库中获取更新的时间戳作为日期时间对象。添加两分钟以获取超时时间。与当前时间进行比较。

ResultSet rs = yourPreparedStatement.executeQuery();
if (rs.next()) {
    OffsetDateTime odt = rs.getObject("your_db_column", OffsetDateTime.class);
    OffsetDateTime currentTime = OffsetDateTime.now(odt.getOffset());
    OffsetDateTime timeoutOdt = odt.plus(TIMEOUT);
    if (currentTime.isAfter(timeoutOdt)) {
        System.out.println("已超时");
    }
    else {
        System.out.println("尚未超时");
    }
}

我假设了一个TIMEOUT类型为Duration的常量。这是灵活的,允许您以分钟、毫秒或其他您喜欢的单位定义超时时间。例如:

private static final String CONFIGUTRED_TIMEOUT = "PT2M"; // 从配置中获取
private static final Duration TIMEOUT = Duration.parse(CONFIGUTRED_TIMEOUT);

配置的超时时间PT2M可能看起来有点奇怪。解读为2分钟的时间段。格式遵循ISO 8601。您还可以尝试使用Duration.ofMinutes(2)Duration.ofMillis(120_000)

如果您的Oracle数据库中的数据类型是timestamp with time zone,这是推荐的做法,您应该能够像示例中展示的那样将其检索为OffsetDateTime。您还可以尝试ZonedDateTimeInstant。如果数据库中的列没有任何时区信息,可以检索为LocalDateTime,然后使用其atZone方法转换为适当的时区。

您之前尝试使用的DateDateFormatSimpleDateFormatTimeZoneTimestamp等日期和时间类都设计不佳且已过时。请避免使用这些类。

英文:

Get your updated timestamp as a date-time object from the database. Add two minutes to obtain the timeout time. Compare to the current time.

    ResultSet rs = yourPreparedStatement.executeQuery();
    if (rs.next()) {
        OffsetDateTime odt = rs.getObject("your_db_column", OffsetDateTime.class);
        OffsetDateTime currentTime = OffsetDateTime.now(odt.getOffset());
        OffsetDateTime timeoutOdt = odt.plus(TIMEOUT);
        if (currentTime.isAfter(timeoutOdt)) {
            System.out.println("Timed out");
        }
        else {
            System.out.println("Not timed out yet");
        }
    }

I have assumed a TIMEOUT constant of type Duration. That's flexible in that it will allow you to define the timeout in minutes or milliseconds or which unit you prefer. For example:

private static final String CONFIGUTRED_TIMEOUT = "PT2M"; // get from configuration
private static final Duration TIMEOUT = Duration.parse(CONFIGUTRED_TIMEOUT);

The configured timeout of PT2M may look funny. Read as a period of time of 2 minutes. The format is ISO 8601. You may alternatively use for example Duration.ofMinutes(2) or Duration.ofMillis(120_000).

If the datatype in your Oracle database is timestamp with time zone, which is recommended, you should be able to retrieve it as an OffsetDateTime as shown. You may also try ZonedDateTime or Instant. If the column in the database hasn't got any time zone, retrieve as LocalDateTime and convert to the proper time zone using its atZone method.

The date and time classes you tried to use, Date, DateFormat, SimpleDateFormat, TimeZone and Timestamp, are all poorly designed and all long outdated. Avoid using those.

huangapple
  • 本文由 发表于 2020年7月26日 20:56:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63100452.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定