我很困惑。在遇到this主题后,我试图弄清楚如何设置格式为hh:mm:ss
的倒数计时器。
这是我的尝试 -
//hh:mm:ss
String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
因此,当我尝试3600000ms
之类的值时,我会得到01:59:00
,这是错误的,因为它应该是01:00:00
。显然我的逻辑有问题,但此刻,我看不出它是什么!
有人可以帮忙吗?
修改
修正了它。这是将毫秒格式化为hh:mm:ss
格式 -
//hh:mm:ss
String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
问题在于TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
。应该是这个TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
而已。
答案 0 :(得分:306)
你真的关闭:
String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
您使用分钟而非小时将小时数转换为毫秒数。
顺便说一句,我喜欢你使用TimeUnit
API:)
这是一些测试代码:
public static void main(String[] args) throws ParseException {
long millis = 3600000;
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(hms);
}
输出:
01:00:00
我意识到我的代码可以通过使用模数除法而不是减法来大大简化:
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
仍然对所有魔术值使用TimeUnit
API,并提供完全相同的输出。
答案 1 :(得分:62)
这种通用方法非常简单:
public static String convertSecondsToHMmSs(long seconds) {
long s = seconds % 60;
long m = (seconds / 60) % 60;
long h = (seconds / (60 * 60)) % 24;
return String.format("%d:%02d:%02d", h,m,s);
}
答案 2 :(得分:49)
如果你正在使用apache commons:
DurationFormatUtils.formatDuration(timeInMS, "HH:mm:ss,SSS");
答案 3 :(得分:21)
// New date object from millis
Date date = new Date(millis);
// formattter
SimpleDateFormat formatter= new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// Pass date object
String formatted = formatter.format(date );
使用1200毫秒的输入查看runnable example。
答案 4 :(得分:19)
我用过这个:
String.format("%1$tH:%1$tM:%1$tS.%1$tL", millis);
请参阅课程Formatter的说明。
使用2400毫秒的输入见runnable example。
答案 5 :(得分:12)
DateFormat df = new SimpleDateFormat("HH:mm:ss");
String formatted = df.format(aDateObject);
答案 6 :(得分:8)
4项实施的测试结果
必须为大量数据进行大量格式化,需要最佳性能,所以这里有(令人惊讶的)结果:
for(int i = 0; i< 1000000; i ++){ FUNCTION_CALL }
持续时间:
formatTimeUnit:2216 millis
public static String apacheFormat(long millis) throws ParseException {
return DurationFormatUtils.formatDuration(millis, "HH:mm:ss");
}
public static String formatTimeUnit(long millis) throws ParseException {
String formatted = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
return formatted;
}
public static String formatDuration(final long millis) {
long seconds = (millis / 1000) % 60;
long minutes = (millis / (1000 * 60)) % 60;
long hours = millis / (1000 * 60 * 60);
StringBuilder b = new StringBuilder();
b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) :
String.valueOf(hours));
b.append(":");
b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :
String.valueOf(minutes));
b.append(":");
b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) :
String.valueOf(seconds));
return b.toString();
}
public static String combinationFormatter(final long millis) {
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
long hours = TimeUnit.MILLISECONDS.toHours(millis);
StringBuilder b = new StringBuilder();
b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) :
String.valueOf(hours));
b.append(":");
b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :
String.valueOf(minutes));
b.append(":");
b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) :
String.valueOf(seconds));
return b.toString();
}
答案 7 :(得分:5)
以下代码以两种方式进行转换
23:59:58:999至86398999
而不是
86398999至23:59:58:999
import java.util.concurrent.TimeUnit;
public class TimeUtility {
public static void main(String[] args) {
long currentDateTime = System.currentTimeMillis();
String strTest = "23:59:58:999";
System.out.println(strTest);
long l = strToMilli(strTest);
System.out.println(l);
l += 1;
String str = milliToString(l);
System.out.println(str);
}
/**
* convert a time string into the equivalent long milliseconds
*
* @param strTime string fomratted as HH:MM:SS:MSMS i.e. "23:59:59:999"
* @return long integer like 86399999
*/
public static long strToMilli(String strTime) {
long retVal = 0;
String hour = strTime.substring(0, 2);
String min = strTime.substring(3, 5);
String sec = strTime.substring(6, 8);
String milli = strTime.substring(9, 12);
int h = Integer.parseInt(hour);
int m = Integer.parseInt(min);
int s = Integer.parseInt(sec);
int ms = Integer.parseInt(milli);
String strDebug = String.format("%02d:%02d:%02d:%03d", h, m, s, ms);
//System.out.println(strDebug);
long lH = h * 60 * 60 * 1000;
long lM = m * 60 * 1000;
long lS = s * 1000;
retVal = lH + lM + lS + ms;
return retVal;
}
/**
* convert time in milliseconds to the corresponding string, in case of day
* rollover start from scratch 23:59:59:999 + 1 = 00:00:00:000
*
* @param millis the number of milliseconds corresponding to tim i.e.
* 34137999 that can be obtained as follows;
* <p>
* long lH = h * 60 * 60 * 1000; //hour to milli
* <p>
* long lM = m * 60 * 1000; // minute to milli
* <p>
* long lS = s * 1000; //seconds to milli
* <p>
* millis = lH + lM + lS + ms;
* @return a string formatted as HH:MM:SS:MSMS i.e. "23:59:59:999"
*/
private static String milliToString(long millis) {
long hrs = TimeUnit.MILLISECONDS.toHours(millis) % 24;
long min = TimeUnit.MILLISECONDS.toMinutes(millis) % 60;
long sec = TimeUnit.MILLISECONDS.toSeconds(millis) % 60;
//millis = millis - (hrs * 60 * 60 * 1000); //alternative way
//millis = millis - (min * 60 * 1000);
//millis = millis - (sec * 1000);
//long mls = millis ;
long mls = millis % 1000;
String toRet = String.format("%02d:%02d:%02d:%03d", hrs, min, sec, mls);
//System.out.println(toRet);
return toRet;
}
}
答案 8 :(得分:5)
public String millsToDateFormat(long mills) {
Date date = new Date(mills);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String dateFormatted = formatter.format(date);
return dateFormatted; //note that it will give you the time in GMT+0
}
答案 9 :(得分:4)
按照波希米亚的回答,我们不需要使用TimeUnit来查找已知值。 更优化的代码将是
String hms = String.format("%02d:%02d:%02d", millisLeft/(3600*1000),
millisLeft/(60*1000) % 60,
millisLeft/1000 % 60);
希望有所帮助
答案 10 :(得分:4)
String string = String.format("%02d:%02d:%02d.%03d",
TimeUnit.MILLISECONDS.toHours(millisecend), TimeUnit.MILLISECONDS.toMinutes(millisecend) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisecend)),
TimeUnit.MILLISECONDS.toSeconds(millisecend) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisecend)), millisecend - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisecend)));
格式:00:00:00.000
示例:615605 Millisecend
00:10:15.605
答案 11 :(得分:4)
标记为正确的答案有一点错误,
String myTime = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
例如,这是我得到的值的一个例子:
417474:44:19
这是获得正确格式的解决方案:
String myTime = String.format("%02d:%02d:%02d",
//Hours
TimeUnit.MILLISECONDS.toHours(millis) -
TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(millis)),
//Minutes
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
//Seconds
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
得到正确的格式:
18:44:19
获取格式hh:mm:ss
的其他选项只是:
Date myDate = new Date(timeinMillis);
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String myTime = formatter.format(myDate);
答案 12 :(得分:3)
我尝试了第一个答案。它有效,但是减去让我感到困惑。我的回答是Groovy:
import static java.util.concurrent.TimeUnit.*
...
private static String formatElapsedTime(long millis) {
int hrs = MILLISECONDS.toHours(millis) % 24
int min = MILLISECONDS.toMinutes(millis) % 60
int sec = MILLISECONDS.toSeconds(millis) % 60
int mls = millis % 1000
sprintf( '%02d:%02d:%02d (%03d)', [hrs, min, sec, mls])
}
答案 13 :(得分:2)
Duration timeLeft = Duration.ofMillis(3600000);
String hhmmss = String.format("%02d:%02d:%02d",
timeLeft.toHours(), timeLeft.toMinutesPart(), timeLeft.toSecondsPart());
System.out.println(hhmmss);
打印:
01:00:00
您正在让图书馆方法为您进行所涉及的转化。 java.time
,现代Java日期和时间API,或者更确切地说,它的Duration
类比TimeUnit
更优雅,更容易出错。
我使用的toMinutesPart
和toSecondsPart
方法是在Java 9中引入的。
long hours = timeLeft.toHours();
timeLeft = timeLeft.minusHours(hours);
long minutes = timeLeft.toMinutes();
timeLeft = timeLeft.minusMinutes(minutes);
long seconds = timeLeft.toSeconds();
String hhmmss = String.format("%02d:%02d:%02d", hours, minutes, seconds);
System.out.println(hhmmss);
输出与上述相同。
java.time
是内置的。org.threeten.bp
导入日期和时间类。java.time
。java.time
。java.time
向Java 6和7的后端(JST-310的ThreeTen)。答案 14 :(得分:1)
嗯,你可以尝试这样的事情:
public String getElapsedTimeHoursMinutesSecondsString() {
long elapsedTime = getElapsedTime();
String format = String.format("%%0%dd", 2);
elapsedTime = elapsedTime / 1000;
String seconds = String.format(format, elapsedTime % 60);
String minutes = String.format(format, (elapsedTime % 3600) / 60);
String hours = String.format(format, elapsedTime / 3600);
String time = hours + ":" + minutes + ":" + seconds;
return time;
}
将毫秒转换为时间值
答案 15 :(得分:1)
对于Kotlin
val hours = String.format("%02d", TimeUnit.MILLISECONDS.toHours(milSecs))
val minutes = String.format("%02d",
TimeUnit.MILLISECONDS.toMinutes(milSecs) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milSecs)))
val seconds = String.format("%02d",
TimeUnit.MILLISECONDS.toSeconds(milSecs) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milSecs)))
其中,milSecs
是毫秒
答案 16 :(得分:1)
这对我和kotlin都有效
fun formatToDigitalClock(miliSeconds: Long): String {
val hours = TimeUnit.MILLISECONDS.toHours(miliSeconds).toInt() % 24
val minutes = TimeUnit.MILLISECONDS.toMinutes(miliSeconds).toInt() % 60
val seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds).toInt() % 60
return when {
hours > 0 -> String.format("%d:%02d:%02d", hours, minutes, seconds)
minutes > 0 -> String.format("%02d:%02d", minutes, seconds)
seconds > 0 -> String.format("00:%02d", seconds)
else -> {
"00:00"
}
}
}
答案 17 :(得分:-2)
在 Kotlin 中:
fun FUNCTION_NAME(milliSeconds: Long): String {
val s: Long = milliSeconds / 1000 % 60
val m: Long = milliSeconds / (1000*60) % 60
val h: Long = milliSeconds / (1000*60*60) % 24
return String.format("%02d:%02d:%02d", h, m, s)
}