0

I wish to get a localized date string. For that, I'm doing:

String dateString = "2019-06-01 00:15:00";
dateString = dateString.replace(" ", "T");
dateString = dateString.concat("Z");

DateFormat dateformat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.FRENCH);
System.out.println(dateformat.format(dateString));

But I'm getting the following exception:

java.lang.IllegalArgumentException: Cannot format given Object as a Date

What could be wrong here?

user5155835
  • 4,392
  • 4
  • 53
  • 97

1 Answers1

1

java.time

    String dateString = "2019-06-01 00:15:00";
    dateString = dateString.replace(" ", "T");
    dateString = dateString.concat("Z");

    DateTimeFormatter formatter = DateTimeFormatter
            .ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.MEDIUM)
            .withLocale(Locale.FRENCH);
    OffsetDateTime dateTime = OffsetDateTime.parse("2019-06-01T00:15:00Z");
    String formattedDateTime = dateTime.format(formatter);

    System.out.println("Formatted date/time: " + formattedDateTime);

Output:

Formatted date/time: 01/06/2019 00:15:00

I recommend you don’t use DateFormat. That class is notoriously troublesome and long outdated. Instead use DateTimeFormatter from java.time, the modern Java date and time API, as shown in my code.

For what went wrong in your code please see the similar question that I link to at the bottom.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161