Home > Net >  How do I parse date String into Date object in Java?
How do I parse date String into Date object in Java?

Time:03-06

how can I parse the following string into Date object in Java: "Wed Feb 16 20:38:34 GMT 01:00 2022"

I was trying to use SimpleDateFormat but was getting the error. Could you help me with that, please? I need to do that in order to use compareTo method afterwards.

Thanks

CodePudding user response:

You can use Java 8 Time API to convert string to LocalDateTime object:

String str = "Wed Feb 16 20:38:34 GMT 01:00 2022";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

Then you can use LocalDateTime compareTo() Method to compare two objects:

int diff = date1.compareTo(date2)
  • Related