Search code examples
javaoracletimetimestampelapsedtime

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


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?


Solution

  • 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.