问题
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));
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?
回答1:
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);
Which can print something like:
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
回答2:
I hope you can try this in Java 8 to get Date from timestamp:
timeStamp.toLocalDateTime().toLocalDate();
For formatting you can use LocalDateTime as:
String str = "1997-03-18 11:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
来源:https://stackoverflow.com/questions/32837406/convert-ms-into-a-string-date-with-java-8