Java Date Parsing with Microsecond or Nanosecond Accuracy

Java date parsing with microsecond or nanosecond accuracy

tl;dr

LocalDateTime.parse(                 // With resolution of nanoseconds, represent the idea of a date and time somewhere, unspecified. Does *not* represent a moment, is *not* a point on the timeline. To determine an actual moment, place this date+time into context of a time zone (apply a `ZoneId` to get a `ZonedDateTime`). 
"2015-05-09 00:10:23.999750900" // A `String` nearly in standard ISO 8601 format.
.replace( " " , "T" ) // Replace SPACE in middle with `T` to comply with ISO 8601 standard format.
) // Returns a `LocalDateTime` object.

Nope

No, you cannot use SimpleDateFormat to handle nanoseconds.

But your premise that…

Java does not support time granularity above milliseconds in its date patterns

…is no longer true as of Java 8, 9, 10 and later with java.time classes built-in. And not really true of Java 6 and Java 7 either, as most of the java.time functionality is back-ported.

java.time

SimpleDateFormat, and the related java.util.Date/.Calendar classes are now outmoded by the new java.time package found in Java 8 (Tutorial).

The new java.time classes support nanosecond resolution. That support includes parsing and generating nine digits of fractional second. For example, when you use the java.time.format DateTimeFormatter API, the S pattern letter denotes a "fraction of the second" rather than "milliseconds", and it can cope with nanosecond values.

Instant

As an example, the Instant class represents a moment in UTC. Its toString method generates a String object using the standard ISO 8601 format. The Z on the end means UTC, pronounced “Zulu”.

instant.toString()  // Generate a `String` representing this moment, using standard ISO 8601 format.

2013-08-20T12:34:56.123456789Z

Note that capturing the current moment in Java 8 is limited to millisecond resolution. The java.time classes can hold a value in nanoseconds, but can only determine the current time with milliseconds. This limitation is due to the implementation of Clock. In Java 9 and later, a new Clock implementation can grab the current moment in finer resolution, depending on the limits of your host hardware and operating system, usually microseconds in my experience.

Instant instant = Instant.now() ;  // Capture the current moment. May be in milliseconds or microseconds rather than the maximum resolution of nanoseconds.

LocalDateTime

Your example input string of 2015-05-09 00:10:23.999750900 lacks an indicator of time zone or offset-from-UTC. That means it does not represent a moment, is not a point on the timeline. Instead, it represents potential moments along a range of about 26-27 hours, the range of time zones around the globe.

Pares such an input as a LocalDateTime object. First, replace the SPACE in the middle with a T to comply with ISO 8601 format, used by default when parsing/generating strings. So no need to specify a formatting pattern.

LocalDateTime ldt = 
LocalDateTime.parse(
"2015-05-09 00:10:23.999750900".replace( " " , "T" ) // Replace SPACE in middle with `T` to comply with ISO 8601 standard format.
)
;

java.sql.Timestamp

The java.sql.Timestamp class also handles nanosecond resolution, but in an awkward way. Generally best to do your work inside java.time classes. No need to ever use Timestamp again as of JDBC 4.2 and later.

myPreparedStatement.setObject( … , instant ) ;

And retrieval.

Instant instant = myResultSet.getObject( … , Instant.class ) ;

OffsetDateTime

Support for Instant is not mandated by the JDBC specification, but OffsetDateTime is. So if the above code fails with your JDBC driver, use the following.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ; 
myPreparedStatement.setObject( … , odt ) ;

And retrieval.

Instant instant = myResultSet.getObject( … , OffsetDateTime.class ).toInstant() ;

If using an older pre-4.2 JDBC driver, you can use toInstant and from methods to go back and forth between java.sql.Timestamp and java.time. These new conversion methods were added to the old legacy classes.

Table of date-time types in Java (both legacy and modern) and in standard SQL


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, and later

    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

using simpledateformat to parse string date with 6 digit of milliseconds

Instead of the long deprecated SimpleDateFormat and java.util.Date, you should use the new DateTimeFormatter and LocalDateTime in the java.time and java.time.format packages. If for no other reason than SimpleDateFormat does not offer nanosecond resolution (and your input appears to have nanoseconds).

Something like,

String date = "2019-07-04 00:32:08:627158";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd HH:m:ss:nnnnnn");
LocalDateTime ldt = LocalDateTime.parse(date, formatter);
DateTimeFormatter outFormatter = DateTimeFormatter.ofPattern(
"dd-MMM-yy hh.mm.ss.nnnnnn a");
System.out.println(outFormatter.format(ldt));

Outputs

04-Jul-19 12.32.08.627158 AM

If you want JUL add a toUpperCase() call, and if you need a literal extra three zeros add them in the outFormatter. Like,

DateTimeFormatter outFormatter = DateTimeFormatter.ofPattern(
"dd-MMM-yy hh.mm.ss.nnnnnn000 a");
System.out.println(outFormatter.format(ldt).toUpperCase());

Outputs

04-JUL-19 12.32.08.627158000 AM

It isn't clear where those three zeros came from, if you wanted more precision I would have used

DateTimeFormatter outFormatter = DateTimeFormatter.ofPattern(
"dd-MMM-yy hh.mm.ss.nnnnnnnnn a");
System.out.println(outFormatter.format(ldt).toUpperCase());

But that outputs (as I would expect)

04-JUL-19 12.32.08.000627158 AM

SimpleDateFormat cannot parse milliseconds with more than 4 digits

It seems that is not possible to use SimpleDateFormat to express times with a finer grain than the millisecond.
What is happening is that as you put 6739, Java understands it as 6739 milliseconds i.e. 6 seconds and 739 milliseconds hence the 6 seconds difference observed.

Check these ones, it is explained quite well:
String-Date conversion with nanoseconds
Java date parsing with microsecond or nanosecond accuracy

Java LocalDateTime.parse with millisecond precision but optional microsecond precision

Hack no. 1

    String withMillis = "2019-02-14 11:04:52.784";
String withMicros = "2019-02-14 11:04:52.784108";

System.out.println(LocalDateTime.parse(withMillis.replace(' ', 'T')));
System.out.println(LocalDateTime.parse(withMicros.replace(' ', 'T')));
2019-02-14T11:04:52.784
2019-02-14T11:04:52.784108

When we replace the space in the middle of your string with a T, the string conforms to ISO 8601, the standard format that LocalDateTime and the other classes of java.time parse (and also print) as their default, that is, without any explicit formatter. So this is an easy solution.

Hack no. 2

Something like what you tried can be made to work. Only you cannot split a sequence of SSSSSS with a square bracket in the middle.

static final DateTimeFormatter DATE_TIME_FORMATTER = 
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.[SSSSSS][SSS]");

And then:

    System.out.println(LocalDateTime.parse(withMillis, DATE_TIME_FORMATTER));     
System.out.println(LocalDateTime.parse(withMicros, DATE_TIME_FORMATTER));

I specify optionally 6 decimals and then optionally 3 decimals. We need that order. If we put [SSS][SSSSSS] and try to parse 6 decimals, the formatter will first parse 3 and then throw an exception because it cannot parse the remaining 3 with SSSSSS. It’s a bit of a hack since it will also accept a decimal point with no decimals at all, and will probably issue a very confusing error message (or possibly even give an incorrect result) if we give it 9 decimals.

The good solution: use a builder

Edit: I have improved the builder a little since the first version of this answer:

static final DateTimeFormatter DATE_TIME_FORMATTER = 
new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();

DateTimeFormatter.ISO_LOCAL_TIME parses from 0 to 9 decimals on the seconds, so we just reuse that formatter in our own formatter.

Original builder:

static final DateTimeFormatter DATE_TIME_FORMATTER = 
new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.appendPattern("HH:mm:ss")
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
.toFormatter();

Here I have specified a minimum of 1 and a maximum of 9 decimals after the decimal point. You can specify 3 and 6 if you prefer. It will of course accept 4 or 5 too.

Link: Wikipedia article: ISO 8601

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

From the documentation of SimpleDateFormat:

Letter     Date or Time Component     Presentation     Examples  
S Millisecond Number 978

So it is milliseconds, or 1/1000th of a second. You just format it with on 6 digits, so you add 3 extra leading zeroes...

You can check it this way:

    Date d =new Date();
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").format(d));

Output:

2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.0132
2013-10-07 12:13:27.00132
2013-10-07 12:13:27.000132

(Ideone fiddle)

What is the date format of 2019-06-17T20:27:23.706000000Z?

Try this:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import java.util.TimeZone;

public class Main
{
public static void main(String[] args){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
try{
Date date = sdf.parse("2019-06-17T20:27:23.706Z");
System.out.println(date);
}
catch(Exception pe){
System.out.println(pe);
}

}
}

output:

Mon Jun 17 20:27:23 UTC 2019

By the way, you can also try this:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'");

Both gives the same result

Try using Instant from java.time package(java 8).

String value = "2019-06-17T20:27:23.706000000Z";
Instant instant = Instant.parse(value);
Date date = Date.from(instant);


Related Topics



Leave a reply



Submit