Home > other >  Convert string to date in Java for given format
Convert string to date in Java for given format

Time:08-09

I have a response from an API for a date field.

"billCycleDate":"2022-07-15T00:00:00-05:00"

I'm trying to convert this to a "dd-MM-yyyy" date format. The easy way is to simply extract the date from the string and then convert into the format I want. But I wanted to know if there is a 'correct' way of doing this.

The following code is what I've been using:

inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss Z", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(localBill.getBillCycleDate(), inputFormatter);
formattedDate = outputFormatter.format(date);

I've tried different patterns ("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", etc.) but none of them seem to work. It throws the following error:

java.time.format.DateTimeParseException: Text '2022-07-15T00:00:00-05:00' could not be parsed at index 19

CodePudding user response:

Try this

inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:sszzz", Locale.ENGLISH);

Reference: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#zzzSpecifier

CodePudding user response:

Try this out.

  DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
  df.setTimeZone(TimeZone.getTimeZone("UTC"));
  
  try {
    return df.parse(dateStr); // pass the string variable which contains the date and time.

// Make sure your string has milliseconds too. Lack of such line will lead to an erroneous value for millisecond.

  } catch (ParseException e) {
    e.printStackTrace();
  }

Let me know if any help is needed.

  • Related