9
votes

What SimpleDateFormat to use for parsing Oracle date ?

I'm using this SimpleDateFormat.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd hh:mm:ss.sss");

its giving this exception.

java.text.ParseException: Unparseable date: "2011-08-19 06:11:03.0"

Kindly please tell me the SimpleDateFormat to use. Thanks.

2
Have you tried using dashes(-) instead of slashes(/) in your format? - DXTR66
If this comes from a DATE field, then do not get it as a string and parse it. - Thorbjørn Ravn Andersen
FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle. - Basil Bourque

2 Answers

14
votes

You should use this Pattern "yyyy-MM-dd HH:mm:ss.S" instead of "yyyy/mm/dd hh:mm:ss.sss".

little h for "Hour in am/pm (1-12)" and H for "Hour in day (0-23)"
see here: SimpleDateFormat

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date date = dateFormat.parse("2011-08-19 06:11:03.0");
2
votes

tl;dr

LocalDateTime.parse( 
    "2011-08-19 06:11:03.0".replace( " " , "T" ) 
) 

Details

Your input string does not match your formatting pattern. Your pattern has slash characters where your data has hyphens.

java.time

Furthermore, you are using terrible old date-time classes that are now legacy, supplanted by the java.time classes.

Your input string nearly complies with the ISO 8601 standard for date-time formats. Replace the SPACE in the middle with a T.

String input = "2011-08-19 06:11:03.0".replace( " " , "T" ) ;

Your input lacks any indicator of time zone or offset-from-UTC. So we parse as a LocalDateTime, for an object lacking any concept of zone/offset.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

To generate a string in standard format, call toString.

String output = ldt.toString() ;

If this input was intended for a specific time zone, assign it.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

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.

With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.

Where to obtain the java.time classes?

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.