-2

I have this code:

private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

Now, I try to format check some String data,

final String format = SIMPLE_DATE_FORMAT.format("2022-12-07T10:57:23.970Z");

I get the error that Cannot format the given Object as a Date. Whats the issue here and how do I resolve it?

Arefe
  • 11,321
  • 18
  • 114
  • 168
  • 1
    You need to pass in an argument of type `Date`, not a `String`. What would be the point of formatting an already formatted date? In addition, you should actually be using the "new" [Java Date-Time APIs](https://docs.oracle.com/javase/8/docs/technotes/guides/datetime/index.html) instead of the legacy date classes. – Robby Cornelissen Dec 07 '22 at 05:19
  • 1
    Please clarify what is your purpose. Do you want to change date format of a string? Or do you want to convert string to Date? – mahfuj asif Dec 07 '22 at 05:23
  • I want to validate if the format is correct for the given string. – Arefe Dec 07 '22 at 05:29
  • 2
    I strongly recommend you don’t use `SimpleDateFormat`. That classes are notoriously troublesome and long outdated. Instead use `DateTimeFormatter` and other classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 07 '22 at 06:17
  • 2
    It would seem to me that you may have forgot to search before asking? This should be easy to find when you paste the exception message into any decent search engine. – Ole V.V. Dec 07 '22 at 06:20
  • 2
    Your string is in ISO 8601 format. Unless you have special format requirements, the simple way to validate it is `Instant.parse("2022-12-07T10:57:23.970Z")`. In this case (the valid case) it succeeds. Had the string been invalid, it would have thrown a `DateTimeParseException`. – Ole V.V. Dec 07 '22 at 06:23
  • Always search Stack Overflow thoroughly before posting. – Basil Bourque Dec 07 '22 at 06:26

1 Answers1

1

There are two issues with your code snippet:

  1. The format method formats a Date object to String. Perhaps, you want to use the parse method which will convert a String to a Date object.
  2. The String you passed is not compliant with the pattern you passed. The Z in the pattern mandates that a timezone should be passed. A valid example would be -0700. An example of this is shown in the javadoc for SimpleDateFormat; just search with yyyy-MM-dd'T'HH:mm:ss.SSSZ.
Wahid Sadik
  • 908
  • 10
  • 24