我正在尝试使用秒的双倍值来转换为自定义时间格式。我已经尝试过SimpleDate Format,但这不起作用......
我有这种格式的双精度值:407.33386569554585
(代表407秒和333毫秒......)。
我需要这种格式:HH/MM/SS.MS
我该怎么做?
提前致谢!
答案 0 :(得分:14)
乘以1,000,然后转换为long
并使用它构建日期。
Date date = new Date((long)(dubTime*1000));
从这里开始,您可以使用SimpleDateFormat制作您喜欢的字符串。
String formattedDate = new SimpleDateFormat("HH/mm/ss.SSS").format(date);
答案 1 :(得分:4)
以Java 8样式(如果您想避免日期弃用警告):
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("HH/mm/ss.SSS").withZone(ZoneId.of("UTC"));
Instant instant = Instant.ofEpochMilli((long)(dubTime*1000));
return formatter.format(instant);
答案 2 :(得分:2)
以下是我们使用的一些您可以轻松适应的代码。下面的实现将打印一个值为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;
}
答案 3 :(得分:1)
只是为了补充蒂姆的答案:无论你的时区如何,都要获得正确的字符串,只需使用SimpleDateFormat.setTimeZone()
:
DateFormat dateFormat = new SimpleDateFormat("HH/mm/ss.SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// ...
double doubleTime=1000.0;
Date date = new Date((long) (doubleTime*1000));
String formattedTime = dateFormat.format(date);
请务必咨询DateFormat.setTimeZone
javadoc,以了解timeZone
何时可能被覆盖。