snippetjavaModerate
Show time in format yyyy-MM-ddThh:mm:ss.SSS
Viewed 0 times
showformatyyyytimeddthhsss
Problem
My requirement is to convert a time (long) to a String with this date format:
yyyy-MM-ddThh:mm:ss.SSS
For instance:
My implementation:
The underscore trick is to avoid the
Also, I am sure more explicit names can be found for
yyyy-MM-ddThh:mm:ss.SSS
For instance:
2017-03-07T03:52:31.298My implementation:
private final static String DATE_FORMAT = "yyyy-MM-dd_hh:mm:ss.SSS";
private final static DateFormat DF =
new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
public static String formatTime(long time) {
return DF.format(time).replace('_', 'T');
}The underscore trick is to avoid the
Illegal pattern character T error I was getting if I had a T character in DATE_FORMAT. I am sure there is a better way to do this?Also, I am sure more explicit names can be found for
DATE_FORMAT/DF?Solution
Don't reinvent the wheel, this is
java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME.long time = System.currentTimeMillis();
ISO_LOCAL_DATE_TIME.format(Instant.ofEpochMilli(time).atZone(ZoneOffset.UTC))
// "2017-03-07T12:09:04.374"Code Snippets
long time = System.currentTimeMillis();
ISO_LOCAL_DATE_TIME.format(Instant.ofEpochMilli(time).atZone(ZoneOffset.UTC))
// "2017-03-07T12:09:04.374"Context
StackExchange Code Review Q#157122, answer score: 16
Revisions (0)
No revisions yet.