Created
August 8, 2016 09:15
-
-
Save Keshava11/fea474e734cb70ec2a2970f4d335fd30 to your computer and use it in GitHub Desktop.
Utility to format time in milliseconds as format hh:mm:ss .
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.utils.formatter; | |
import java.util.IllegalFormatException; | |
import java.util.concurrent.TimeUnit; | |
import org.apache.commons.lang3.time.DurationFormatUtils; | |
public class TimeFormatter { | |
private static final String DURATION_FORMAT = "%02d:%02d:%02d"; | |
private static final String DURATION_FORMAT_OTHER = "HH:mm:ss"; | |
/** | |
* Method uses {@link TimeUnit}'s class conversion to format time | |
* @param iMillis | |
* time as milliseconds | |
* @return formatted time duration | |
*/ | |
public String formartDuration(long iMillis) { | |
String hms = ""; | |
try { | |
hms = String.format( | |
DURATION_FORMAT, | |
TimeUnit.MILLISECONDS.toHours(iMillis), | |
TimeUnit.MILLISECONDS.toMinutes(iMillis) | |
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS | |
.toHours(iMillis)), | |
TimeUnit.MILLISECONDS.toSeconds(iMillis) | |
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS | |
.toMinutes(iMillis))); | |
} catch (IllegalFormatException | NullPointerException e) { | |
e.printStackTrace(); | |
} | |
return hms; | |
} | |
/** | |
* Method uses {@link TimeUnit}'s class conversion to format time | |
* @param iMillis | |
* time as milliseconds | |
* @return formatted time duration | |
*/ | |
public String formartDurationOther(long iMillis) { | |
String hms = ""; | |
try { | |
hms = String.format( | |
DURATION_FORMAT, | |
TimeUnit.MILLISECONDS.toHours(iMillis), | |
TimeUnit.MILLISECONDS.toMinutes(iMillis) | |
% TimeUnit.HOURS.toMinutes(1), | |
TimeUnit.MILLISECONDS.toSeconds(iMillis) | |
% TimeUnit.MINUTES.toSeconds(1)); | |
} catch (IllegalFormatException | NullPointerException e) { | |
e.printStackTrace(); | |
} | |
return hms; | |
} | |
/** | |
* Method uses {@link DurationFormatUtils}'s format method to format | |
* | |
* @param iMillis | |
* time as milliseconds | |
* @return formatted time duration | |
*/ | |
public String formartDurationAnother(long iMillis) { | |
return DurationFormatUtils.formatDuration(iMillis, DURATION_FORMAT_OTHER); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment