使用Java 8将ms转换为字符串日期 [英] Convert ms into a string date with Java 8
问题描述
我有一个时间戳(毫秒),并使用SimpleDateFormater对其进行格式化,如下所示:
I have a timestamp as ms and format this with a SimpleDateFormater like this:
SimpleDateFormat sdfDate = new SimpleDateFormat("MM/d/yyyy h:mm a");
return sdfDate.format(new Date(timeStamp));
现在,我想更改它以使用新的Java 8功能.似乎我真的找不到一种方法来使用新的Java 8类.有提示吗?
Now I'd like to change this to use the new Java 8 abilities. Seems like I really can't find a way to get this working with the new Java 8 Classes. Anyone got a hint?
推荐答案
如果您所拥有的只是毫秒值(假设从Unix Epoch开始),则可以使用以下命令获取LocalDateTime
:
If all you have is a millisecond value (assuming from the Unix Epoch) you can get an LocalDateTime
using something like:
LocalDateTime ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(timeInMillis), ZoneId.systemDefault());
System.out.println(ldt);
可以打印以下内容:
2015-09-29T16:57:40.077
然后您可以使用以下格式进行格式化:
You can then format it using something like this:
System.out.println(ldt.format(DateTimeFormatter.ofPattern("MM/dd/yyyy h:mm a")));
可以打印类似的内容(基于上一个示例的原始时间):
Which can print something like (based on the original time from the previous example):
09/29/2015 4:57 PM
这篇关于使用Java 8将ms转换为字符串日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!