-2
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss");

OR

java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss");

I have the format of time in data bases tables and I have to convert them into yyyy-MM-dd HH:mm:ss or MM/dd/YYYY HH:mm:ss

Input : Mon Jan 21 2019 20:06:48 GMT-0400 (EDT)

Expected output : 01/21/2019 20:06:48

PKR_2193
  • 1
  • 1
  • What is the question? – Costantino Grana Apr 16 '19 at 20:49
  • 2
    You'll need two `DateTimeFormatter` objects (or equivalent) - one to parse your `String`, and another to format the result. – Dawood ibn Kareem Apr 16 '19 at 20:57
  • If your date and time are stored as `datetime` or `timestamp` in your database, don’t get then as a string. A modern JDBC driver or JPA implementation will be happy to get them as an appropriate type from java.time for you (for example `OffsetDateTime`). – Ole V.V. Apr 17 '19 at 06:13
  • I recommend you don’t use `SimpleDateFormat`. That class is notoriously troublesome and long outdated. If you do need parsing and also for formatting use `DateTimeFormatter` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 17 '19 at 06:14

1 Answers1

0

21 January, 2019 is a Monday not a Thursay, Java'll throws an error when parsing


You need an formatter to parse your string, and a formatter to print the date like you want

  • if your system use by default Locale.ENGLISH you can remove it) :

String input = "Mon Jan 21 2019 20:06:48 GMT-0400 (EDT)";

DateTimeFormatter inFormatter = DateTimeFormatter.ofPattern("EE MMM dd yyyy HH:mm:ss 'GMT'xx (z)");
DateTimeFormatter outFormatter = DateTimeFormatter.ofPattern("MM/dd/yy HH:mm:ss");

OffsetDateTime od = OffsetDateTime.parse(input, inFormatter);

System.out.println(od);                         // 2019-01-21T20:06:48-04:00
System.out.println(od.format(outFormatter));    // 01/21/19 20:06:48
azro
  • 53,056
  • 7
  • 34
  • 70
  • 1
    Close, but that is not the input string (ignoring the day-of-week issue), you're missing the `(EDT)` at the end of the input. – Andreas Apr 16 '19 at 21:27
  • @Andreas done ;) – azro Apr 16 '19 at 22:17
  • 2
    Wouldn't it be easier to just use pattern `"EE MMM dd yyyy HH:mm:ss 'GMT'xx (z)"`? – Andreas Apr 16 '19 at 22:39
  • I agree with @Andreas here. You are parsing `GMT` into a time zone that is not the time zone of the time, which `OffsetDateTime` then fortunately ignores. Requiring `'GMT'` littterally would seem to avoid any confusion. – Ole V.V. Apr 17 '19 at 06:39
  • @Andreas sure, my bad – azro Apr 17 '19 at 06:55