tl;dr
I have an Oracle Date type stored in the db in this format 06-MAR-20
No, you don’t.
- Databases such as Oracle store date-time values with their own internally defined binary values, not as plain text.
- Oracle
DATE
type holds a time-of-day as well as a date.
DATE
= date + time-of-day
The DATE
type in Oracle database is misnamed. It holds more than a date (year, month, and day-of-month).
This type represents a date with time-of-day resolving to whole seconds. This type lacks the context of a time zone or offset-from-UTC. So this type cannot be used to represent a moment, a specific point on the timeline. (To track a moment, use Oracle type TIMESTAMP WITH TIME ZONE
.)
Note that this Oracle naming differs from the SQL standard. In the standard, a DATE
type is a date-only value, with no time-of-day and no time zone or offset.
java.time.LocalDateTime
So this type maps to LocalDateTime
in Java.
Retrieval.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
Storage.
myPreparedStatement.setObject( … , ldt ) ;
Text
Notice that in the code above we are using smart objects rather than dumb strings.
Date-time objects such as LocalDateTime
are not String
and do not hold text. They internally represent their value in their own way. You can parse a string as a date-time object, and you can ask the date-time object to generate text. But the text and the date-time object are separate and distinct.
The java.time classes use standard ISO 8601 formats when parsing/generating strings.
String output = ldt.toString() ;
2020-01-23T01:23:45.123456789
Parsing.
You can generate text in other formats. You can specify your own custom format by calling DateTimeFormatter.ofPattern
. Usually better to automatically format by calling DateTimeFormatter.ofLocalized…
methods.
This has been covered many many times already on Stack Overflow. So search to learn more.
LocalDateTime ldt = LocalDateTime.parse( "2020-01-23T01:23:45.123456789" ) ;
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?