0

We are getting a date from an API in string and the format is RFC3339. I need to convert this into a timestamp in this format 20-MAR-22 12.00.00.00.000000000 AM

I tried using Timestamp.valueOf(objUs.getUserAcptDate) but here we are getting an exception.

I found by searching online RFC3339 is in this formate "2019-10-12T07:20:50.52Z" or it may be without T.

How can we convert the coming string from API into a timestamp and this is the formate which we are saving in DB 20-MAR-22 12.00.00.00.000000000 AM

Learners
  • 121
  • 11
  • 1
    See `LocalDateTime` – Ryan Apr 12 '22 at 18:04
  • 1
    *and this is the formate which we are saving in DB 20-MAR-22 12.00.00.00.000000000 AM* Your db column has a character type to hold a date? If so, it shouldn't. – g00se Apr 12 '22 at 18:29
  • @g00se Is correct and a bit more. I hope you are using a `timestamp`, best `with time zone` in your database. Since JDBC 4.2 you can and should pass java.time types to your database such as `OffsetDateTime`, `Instant` or `LocalDateTime`. See for example [Dates with no time or timezone component in Java/MySQL](https://stackoverflow.com/questions/285553/dates-with-no-time-or-timezone-component-in-java-mysql). Hibernate will be fine with doing the same. So use no string for it. – Ole V.V. Apr 12 '22 at 20:37

1 Answers1

1

You could use DateTimeFormatter to parse/format date-time objects. There are many predefined formatters or you could build custom if required. For some advanced scenarios you could use DateTimeFormatterBuilder that provides many different options for parsing and formatting.

private static final DateTimeFormatter CUSTOM_DATE = DateTimeFormatter.ofPattern("dd-MMM-yy hh.m.ss.n a");
private static final DateTimeFormatter ISO_DATE = DateTimeFormatter.ISO_ZONED_DATE_TIME;


String input = "2019-10-12T07:20:50.52Z";
ZonedDateTime date = ZonedDateTime.parse(input, ISO_DATE);
String output = CUSTOM_DATE.format(date);
Alex
  • 4,987
  • 1
  • 8
  • 26
  • 1
    That should work. Only `.n` for the decimal part in the format pattern string is dangerous. If the time has, say 23.01 seconds, they wil come out as 23.10000000 where you would have wanted 23.010000000. I suggest `.SSSSSSSSS` for the decimal part. You should also specify a locale for the formatter to make sure the month abbreviation will be in English. – Ole V.V. Apr 12 '22 at 20:34