Java : human readable date time difference

Using Apache Commons Duration Format Utils date-time differences can be formatted pretty easily. It formats just like SimpleDateFormatter :

  1. import org.apache.commons.lang.time.DurationFormatUtils;
  2. //...
  1. Date startTime = new Date();
  2. //...
  3. //... lengthy jobs
  4. //...
  5. Date endTime = new Date();
  6. long diff = endTime.getTime() - startTime.getTime();
  7. String hrDateText = DurationFormatUtils.formatDuration(diff, "d 'day(s)' H 'hour(s)' m 'minute(s)' s 'second(s)' ");
  8. System.out.println("Duration : " + hrDateText);

Sample Output the code:
0 days(s) 0 hour(s) 0 minute(s) 1 second(s)

Maven dependency:

  1. <dependency>
  2.     <groupId>org.apache.commons</groupId>
  3.     <artifactId>commons-lang3</artifactId>
  4.     <version>3.3.2</version>
  5. </dependency>

No comments:

Post a Comment