Monday 16 July 2018

Java: Convert the current time to HOURS:MINUTES:SECONDS:MILLISECONDS format



Find the below working application.

Test.java
package com.sample.app;

public class Test {

 /**
  * Convert the current time to HOURS:MINUTES:SECONDS:MILLISECNODE format.
  * 
  * @return
  */
 private static String getCurrentTime() {
  return getTime(System.currentTimeMillis());
 }

 /**
  * Convert the current time to HOURS:MINUTES:SECONDS:MILLISECNODE format.
  * 
  * @param milliSeconds
  * @return
  * 
  * @throws IllegalArgumentException if milliSeconds <= 0
  */
 private static String getTime(final long milliSeconds) {
  if (milliSeconds <= 0) {
   throw new IllegalArgumentException("Time can't be negative");
  }

  long seconds = milliSeconds / 1000;
  long milliSec = milliSeconds % 1000;

  long minutes = seconds / 60;
  seconds = (seconds % 60);

  long hours = minutes / 60;
  minutes = minutes % 60;

  return hours + "h:" + minutes + "m:" + seconds + "s:" + milliSec + "ms";
 }

 public static void main(String args[]) {
  System.out.println(getCurrentTime());
 }
}


You may like


Previous                                                    Next                                                    Home

No comments:

Post a Comment