其他答案都是正确的,并且是 2013 年问这个问题时的好答案。今天我们不应该再使用 Date 或 SimpleDateFormat,所以我想向您展示几个现代代码 sn-ps 代替.格式化(在这种情况下)2 305 293 毫秒的正确方法取决于它们所代表的内容。我针对三种不同的情况提出了三种选择。
格式化自纪元以来的毫秒数
您需要决定要在哪个时区解释您的时间点。例如:
long millis = 2_305_293L;
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.ENGLISH);
ZonedDateTime dateTime = Instant.ofEpochMilli(millis)
.atZone(ZoneId.of("America/Coral_Harbour"));
String formattedTime = dateTime.format(formatter);
System.out.println(formattedTime);
美国东部标准时间 1969 年 12 月 31 日晚上 7:38:25
由于纪元珊瑚港的 UTC 偏移量为 -05:00,因此我们得到的时间接近 1969 年底。如果您想要 UTC 时间(因为纪元是用 UTC 定义的;换句话说,如果您想要00:38:25),有点不一样:
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(Locale.ENGLISH);
OffsetDateTime dateTime = Instant.ofEpochMilli(millis)
.atOffset(ZoneOffset.UTC);
1970 年 1 月 1 日上午 12:38:25
除了时区之外,您还可以通过区域设置来改变语言,通过格式样式(完整、长、中、短)来改变格式的长度。如果您想要没有日期的时间,请使用ofLocalizedTime 而不是ofLocalizedDateTime。
格式化一天中的毫秒
假设您的毫秒是从 0:00(“午夜”)开始在任何时区:
LocalTime time = LocalTime.MIN.with(ChronoField.MILLI_OF_DAY, millis);
System.out.println(time);
00:38:25.293
如果此格式令人满意,则不需要任何显式格式化程序。如果没有,您可以使用DateTimeFormatter。
格式化持续时间,时间量
时间量与时间完全不同,它作为Duration 对象处理。没有对格式化的直接支持,但从 Java 9 开始就不那么难了(当你知道怎么做的时候):
Duration amountOfTime = Duration.ofMillis(millis);
String formattedTime = String.format("%02d:%02d:%02d",amountOfTime.toHours(),
amountOfTime.toMinutesPart(), amountOfTime.toSecondsPart());
System.out.println(formattedTime);
00:38:25
链接
Oracle tutorial: Date Time 解释如何使用 java.time。