Oracle date to Java date
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.
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");
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.
上一篇: Java SimpleDateFormat解析后错误的时区
下一篇: Oracle日期到Java日期