0

I am using java timer, but my problem is every time exceeding 60 seconds, I like my code working like;

1 minutes 59 seconds, 2 minutes 0 seconds..

My code is below.

private long lastReceivedMessage = System.currentTimeMillis();
    
@Scheduled(fixedDelayString = "${listenScheduled}", initialDelay = 1000)
private void distanceBetweenLastReceivedMessageAndCurrentTime() {
    long currentTime = System.currentTimeMillis() - lastReceivedMessage;
    logger.info("has threw 'INFO' event due to is not running as an expected since {} {} {} {} ", TimeUnit.MILLISECONDS.toMinutes(currentTime), "minutes", TimeUnit.MILLISECONDS.toSeconds(currentTime), "seconds");
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
john deltana
  • 37
  • 1
  • 6
  • Does this answer your question? [How to convert milliseconds to "hh:mm:ss" format?](https://stackoverflow.com/questions/9027317/how-to-convert-milliseconds-to-hhmmss-format) – Étienne Miret Jul 01 '21 at 14:14

2 Answers2

1

java.time classes

Capture the current moment using java.time.Instant.

Instant then = Instant.now() ;
…
Duration d = Duration.between( then , Instant.now() ) ;
String output = d.toString() ;

The toString method generates text in standard ISO 8601 format: PnYnMnDTnHnMn. I suggest you report using that format. The format uses a P to mark the beginning. A T separates any years-months-days from any hours-minutes-seconds. So, two and a half minutes is PT2M30S.

If you insist on your format, call the to…Part methods on Duration.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • @johndeltana - This is indeed the idiomatic way of solving your problem. Just keep in mind that `Duration` gives a directed value i.e. a duration may be negative. Also, the `to...Part` was introduced with Java-9 (not with Java-8 which introduced `java.time` API). Learn more about the modern Date-Time API from **[Trail: Date Time](https://docs.oracle.com/javase/tutorial/datetime/index.html)**. – Arvind Kumar Avinash Jul 02 '21 at 15:51
0

It is not going to automatically separate the minutes and seconds. Also, I would recommend breaking up that logger.info statement for readability.

One way to do it is to convert it to seconds first, set the modulus (remainder) of the seconds and 60 as your seconds, then divide the minutes for the minutes value. Or you could just skip the conversion and divide + modulus by 60000.

long msElapsed = 660_000; //5min 30sec

long secElapsed = msElapsed / 1000;

long minutes = secElapsed / (long) 60;

long seconds = secElapsed % 60;

System.out.printf("%d %d",(int)minutes,(int)seconds);