Friday, September 21, 2018

Change data format of string with nanotime since JDK8

Problem:

When I use JMC 6.0 API to parse JFR recordings for humongous objects (will post another blog for it), end time is string with nanotime (e.g, 8/29/2018, 3:33:00.536521391 PM) . Objective is format the data string like yyyy-MM-dd'T'HH:mm:ss.n.

Solution:

SimpleDataFormat in JDK doesn't support nanotime (https://docs.oracle.com/javase/10/docs/api/index.html?overview-summary.html), Joda support it, and Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310). (http://www.joda.org/joda-time/), so we can use java.time from JDK8.

Sample code:

String input = "8/29/2018, 3:33:00.536521391 PM";
DateTimeFormatter oldPattern = DateTimeFormatter.ofPattern("M/d/y',' h:m:s.n a");
DateTimeFormatter newPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.n");
LocalDateTime datetime = LocalDateTime.parse(input, oldPattern);

No comments:

Post a Comment