I have an Oracle Date type stored in the db in this format 06-MAR-20, when i mapped it to a java domain class i had a property of type
java.SQL.Date
but i got the data in this format
2020-03-06
How can i stick to the exact same format from whats stored in my db? Will
java.SQL.Timestamp
keep it the same?
Or do i need to do some configuration when getting the data from query to maintain its format?
I have an Oracle Date type stored in the db in this format 06-MAR-20
No, you don’t.
DATE type holds a time-of-day as well as a date.DATE = date + time-of-dayThe 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.LocalDateTimeSo this type maps to LocalDateTime in Java.
Retrieval.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
Storage.
myPreparedStatement.setObject( … , ldt ) ;
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" ) ;
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With