0

I have a string date "04/01/2020 at 9:00PM". I would like to convert it into an ISO date format. Looking for optimizing way to convert it into ISO date format

Satish
  • 59
  • 3
  • 14

1 Answers1

2

Try this code:

    public static void main(String[] args) {
        String dateString = "04/01/2020 at 9:00PM";
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy 'at' hh:mma");

        try {
            Date date = dateFormat.parse(dateString);
            System.out.println(date);
        } catch(ParseException exception) {
            System.out.println(exception.getMessage());
        }
    }

Checkout this post for more information: https://stackoverflow.com/a/4216767/10030693

UPDATE

Following advise from Mark Rotteveel, DateTimeFormatter is a better API to use to format date in java 8, so this should be preferred:

   public static void main(String[] args) {
        String dateString = "12/12/2020 at 09:00PM";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("d/M/yyyy 'at' hh:mma", Locale.ENGLISH);
        try {
            LocalDateTime dateTime = LocalDateTime.parse(dateString, dateTimeFormatter);
            System.out.println(dateTime);
        } catch (DateTimeException exception) {
            System.out.println(exception.getMessage());
        }
    }
Gilbert
  • 2,699
  • 28
  • 29
  • 2
    I'd recommend switching to the `java.time` formatters instead of using the older classes like `SimpleDateFormat` – Mark Rotteveel Apr 22 '20 at 11:03
  • I have tried but I can't really get my head around DateTimeFormatter following this [post](https://stackoverflow.com/a/4216767/10030693). Maybe you could post a solution that uses DateTimeFormatter – Gilbert Apr 22 '20 at 12:29
  • 1
    @MarkRotteveel I have updated my answer. Thanks – Gilbert Apr 22 '20 at 12:41
  • 1
    ISO date format was asked for. While the first example doesn’t provide that, the example using [java.time, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) does print ISO 8601 format since tha java.time classes do that natively. The output is `2020-12-12T21:00`. – Ole V.V. Apr 22 '20 at 16:07
  • Thank you. The solution is working for me. – Satish Apr 25 '20 at 03:32