Dưới đây là một số mã chúng tôi sử dụng mà bạn có thể dễ dàng điều chỉnh. Việc thực hiện dưới đây sẽ in một giá trị như 00days 00h00m00s00ms:
public final static long ONE_MILLISECOND = 1;
public final static long MILLISECONDS_IN_A_SECOND = 1000;
public final static long ONE_SECOND = 1000;
public final static long SECONDS_IN_A_MINUTE = 60;
public final static long ONE_MINUTE = ONE_SECOND * 60;
public final static long MINUTES_IN_AN_HOUR = 60;
public final static long ONE_HOUR = ONE_MINUTE * 60;
public final static long HOURS_IN_A_DAY = 24;
public final static long ONE_DAY = ONE_HOUR * 24;
public final static long DAYS_IN_A_YEAR = 365;
public String formatHMSM(Number n) {
String res = "";
if (n != null) {
long duration = n.longValue();
duration /= ONE_MILLISECOND;
int milliseconds = (int) (duration % MILLISECONDS_IN_A_SECOND);
duration /= ONE_SECOND;
int seconds = (int) (duration % SECONDS_IN_A_MINUTE);
duration /= SECONDS_IN_A_MINUTE;
int minutes = (int) (duration % MINUTES_IN_AN_HOUR);
duration /= MINUTES_IN_AN_HOUR;
int hours = (int) (duration % HOURS_IN_A_DAY);
duration /= HOURS_IN_A_DAY;
int days = (int) (duration % DAYS_IN_A_YEAR);
duration /= DAYS_IN_A_YEAR;
int years = (int) (duration);
if (days == 0) {
res = String.format("%02dh%02dm%02ds%03dms", hours, minutes, seconds, milliseconds);
} else if (years == 0) {
res = String.format("%ddays %02dh%02dm%02ds%03dms", days, hours, minutes, seconds, milliseconds);
} else {
res = String.format("%dyrs %ddays %02dh%02dm%02ds", years, days, hours, minutes, seconds);
}
}
return res;
}
Nguồn
2011-11-13 23:45:45
Làm thế nào để giá trị nhận được trong đó biến đôi? Và làm thế nào là giá trị tăng gấp đôi được xây dựng - Tôi không thể nhìn thấy bất kỳ giây nào nữa :) – saintedlama
Đồng ý, điều gì làm tăng gấp đôi đó đại diện cho? – Lucas
Bạn có thể nhận được một vài ý tưởng tại đây: http://stackoverflow.com/questions/266825/how-to-format-a-duration-in-java-eg-format-hmmss –