java.time
Quickest to write:
LocalDate.parse(
"03/12/2012" ,
DateTimeFormatter.ofPattern( "MM/dd/uuuu" )
).toString()
Your desired output happens to comply with the ISO 8601 standard for formatting date-time strings. The java.time classes use those standard formats when parsing and generating strings representing their value.
The java.time.LocalDate
class is built into Java 8 and later, and represents a date-only value without time-of-day and without time zone.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Quickest to execute?
If we cache the DateTimeFormatter
, the cost of each parse-a-string-to-generate-a-string takes a third of a microsecond, 300-400 nanoseconds, when running in NetBeans 8.2 under Java 8 Update 111 on a MacBook Pro (Retina, 15-inch, Late 2013) (2.3 GHz Intel Core i7 processor) (16 GB 1600 MHz DDR3) (macOS El Capitan).
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MM/dd/uuuu" );
int limit = 100_000_000; // Number of iterations of parsing a string to generate a string.
long start = System.nanoTime ();
for ( int i = 0 ; i < limit ; i ++ ) {
String s = LocalDate.parse ( "03/12/2012" , f ).toString ();
}
long stop = System.nanoTime ();
long elapsedNanos = ( stop - start );
long elapsedSeconds = TimeUnit.NANOSECONDS.toSeconds ( elapsedNanos );
long eachNanos = ( elapsedNanos / limit );
System.out.println ( "For limit of " + limit + " took seconds: " + elapsedSeconds + " and each iteration took nanoseconds: " + eachNanos );
For limit of 100000000 took seconds: 33 and each iteration took nanoseconds: 332
Instantiating the DateTimeFormatter
seems to take about 200 nanoseconds, nearly doubling the execution time. Change one line of code above, to replace the argument f
.
String s = LocalDate.parse ( "03/12/2012" , DateTimeFormatter.ofPattern ( "MM/dd/uuuu" ) ).toString ();
For limit of 100000000 took seconds: 54 and each iteration took nanoseconds: 542
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 java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 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 SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
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.