0

Through PostgreSQL I received date-time like this format

2022-11-28 23:36:43.712

Anyone know how to convert this to following format in Java

Mon Nov 28 20:51:58 IST 2022

or its ok to convert Mon Nov 28 20:51:58 IST 2022 to 2022-11-28 23:36:43.712 format.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 3
    Retrieve it as a LocalDateTime, then use a `DateTimeFormatter` to format it as a string –  Nov 28 '22 at 18:29
  • 1
    Your target type is `ZonedDateTime` – g00se Nov 28 '22 at 18:43
  • 2
    What *exactly* is the data type of your column? – Basil Bourque Nov 28 '22 at 18:49
  • 2
    “reserved”? Is that a typo? – Basil Bourque Nov 28 '22 at 18:50
  • 3
    As @a_horse_with_no_name probably already meant to say, do not retrieve your date and time as a string from your database. Retrieve a `LocalDateTime`. See for example [this question](https://stackoverflow.com/questions/29773390/getting-the-date-from-a-resultset-for-use-with-java-time-classes). – Ole V.V. Nov 28 '22 at 20:33
  • 1
    In which time zone is the value in the database? And in which time zone do you want the output? – Ole V.V. Nov 29 '22 at 09:55
  • 1
    `retrievedLocalDateTime .atZone(dbZone) .withZoneSameInstant(userZone) .format(DateTimeFormatter.ofPattern("EEE MMM d H:mm:ss.SSS zzz u", Locale.ENGLISH))` where `dbZone` and `userZone` are appropriate `ZoneId` or `ZoneOffset` objects. If the former is UTC and the latter Asia/Tel_Aviv, the result is `Tue Nov 29 1:36:43.712 IST 2022`. – Ole V.V. Nov 29 '22 at 16:29

1 Answers1

2
DateTimeFormatter formatterIn = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); 
ZonedDateTime yourDate = ZonedDateTime.parse("2022-11-28 23:36:43.712", formatterIn.withZone(ZoneId.of("UTC")));

DateTimeFormatter formatterOut = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"); 
String yourDateFormatted = formatterOut.format(yourDate);

System.out.println(yourDateFormatted);

And if you are in India you can take ZoneId.of("Asia/Calcutta")

Vladimir.V.Bvn
  • 1,050
  • 1
  • 13
  • 13