0

I have oracle database with columns data type "TIMESTAMP(0) WITH TIME ZONE" . Which produces like 14/11/2019 06:30:00, +03:00 in database .

When I am trying to get this timestamp from java I got java.text.ParseException: Unparseable date: "28-MAY-12 07.40.03 PM +03:00" . Our project java version is 6 . I tried with

      new SimpleDateFormat("dd-MM-yy hh.mm.ss") ,
      new SimpleDateFormat("dd-MM-yy hh.mm.ss, Z"),
      new SimpleDateFormat("dd-MM-yy hh.mm.ss, z")  ,
      new SimpleDateFormat("dd/MM/yy hh.mm.ss, z") ,
      new SimpleDateFormat("dd/MM/yy hh.mm.ss, Z") ,
      new SimpleDateFormat("dd/MM/yy hh.mm.ss")

But none of them worked for me all of throwing java.text.ParseException: Unparseable date error.

In my java side i have date datatype property in my class and i want to retrieve data from oracle database then parse then set to date data type property like below.

serDto.setTarih(new Timestamp(new SimpleDateFormat("dd-MM-yy hh.mm.ss").parse(str).getTime()));

For ex in db timestamp data looks like : 14/11/2019 06:30:00, +03:00 and i want to retrieve as date like above.

Thank you in advance.

Samet Dağ
  • 137
  • 5
  • 20
  • Where does the string you are trying to parse come from? Is there maybe a way to change its format to something that's easier to parse? – Joni Jul 12 '20 at 15:41
  • I am reading xml document element like element.getElementsByTagName("PLZ_ID").item(0).getTextContent() to str then trying to parse. – Samet Dağ Jul 12 '20 at 15:51
  • I recommend you don’t use `SimpleDateFormat`, `Date` and `Timestamp`. Those classes are poorly designed and long outdated, the first in particular notoriously troublesome. Instead fetch an `OffsetDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) from your database. Then you may need no parsing. – Ole V.V. Jul 12 '20 at 17:08

1 Answers1

0

A partial solution is changing the pattern so that it parses the name of the month and the am/pm marker. Change MM to MMM and add a:

new SimpleDateFormat("dd-MMM-yy hh.mm.ss a").parse(str)

However this will ignore the time zone information. It will return a date with the expected time (i.e. 07:40:03 PM) in the default local time zone where this code is running, which might be different from the time zone in the input GMT+0300.

There doesn't seem to be a way to parse +03:00 into a time zone with SimpleDateFormat in Java 6, so if you need to parse the time zone this will require more custom code.

Joni
  • 108,737
  • 14
  • 143
  • 193