如何解决我可以从毫秒值中获得Curren时间的价值吗
我的值以毫秒为单位 1601626934449
通过https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()生成的
但是我能以某种方式以人类可读的格式获取时间吗?或者简而言之,我需要知道毫秒 1601626934449 的值是多少?
解决方法
您可以将毫秒转换为LocalDateTime
来存储时间
long millis = System.currentTimeMillis();
LocalDateTime datetime = Instant.ofEpochMilli(millis)
.atZone(ZoneId.systemDefault()).toLocalDateTime();
然后,您可以使用toString()
打印数据,或使用DateTimeFormatter
打印所需格式。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
System.out.println(datetime.format(formatter));
输出:2020-10-02 18:39:54.609
在Java 8或更高版本上使用java.time
。使用它,很容易达到您的目标。
您基本上是从纪元毫秒(代表时间)创建一个Instant
,通过应用ZonedDateTime
(在下面的示例中系统的默认设置)使其成为ZoneId
通过内置String
格式化输出DateTimeFormatter
或通过创建具有所需模式的自定义格式来使输出public static void main(String[] args) {
// your example millis
long currentMillis = 1601626934449L;
// create an instant from those millis
Instant instant = Instant.ofEpochMilli(currentMillis);
// use that instant and a time zone in order to get a suitable datetime object
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant,ZoneId.systemDefault());
// then print the (implicitly called) toString() method of it
System.out.println(currentMillis + " is " + zdt);
// or create a different human-readable formatting by means of a custom formatter
System.out.println(
zdt.format(
DateTimeFormatter.ofPattern(
"EEEE,dd. 'of' MMMM uuuu 'at' HH:mm:ss 'o''clock in' VV 'with an offset of' xxx 'hours'",Locale.ENGLISH
)
)
);
}
易于人类阅读。
这是一个例子:
1601626934449 is 2020-10-02T10:22:14.449+02:00[Europe/Berlin]
Friday,02. of October 2020 at 10:22:14 o'clock in Europe/Berlin with an offset of +02:00 hours
输出(在我的系统上)
{{1}},
您可以创建一个Date对象并将其用于获取所需的所有信息:
https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#Date(long)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。