Microseconds in Java








SimpleDateFormat in java does not support microseconds. It supports down to milliseconds only.
In some cases, we want to parse Time from string, which includes microseconds, or format a Date/Time to a string (with microseconds).
Here are some sample java code to work around this problem.

public class DateTimeUtil {

   public static final String FORMAT_PATTERN = "yyyyMMddHHmmss.SSS000";

   public static Date parse(String ds) throws Throwable {

    String[] tokens = ds.split("\\.");
    if (tokens.length != 2) {
     throw new Exception("Invalid date string: " + ds);
    }
    int fractionalSecs = Integer.parseInt(tokens[1]) / 1000;
    return new SimpleDateFormat("yyyyMMddHHmmss.SSS").parse(String.format("%s.%03d", tokens[0], fractionalSecs));
   }

   public static String format(Date date) {
  
    return new SimpleDateFormat(FORMAT_PATTERN).format(date);
   }

}


See also http://stackoverflow.com/questions/2132247/custom-date-format-cannot-be-parsed-java


No comments:

Post a Comment