1

How can I create an instance of java.util.Date out of a custom date time string? This is what I tried so far:

Given I have the this custom date time string:

Fri Jul 29 12:56:35 UTC 2022

Using Joda-Time in the following piece of code:

String time = "Fri Jul 29 12:56:35 UTC 2022";
DateTimeFormatter df = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss z yyyy");
long millis = df.parseMillis(time);

I get the following exception:

java.lang.IllegalArgumentException: Invalid format: "Fri Jul 29 12:56:35 UTC 2022" is malformed at " UTC 2022"
        at org.joda.time.format.DateTimeFormatter.parseMillis(DateTimeFormatter.java:644)
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Amine
  • 901
  • 2
  • 14
  • 33
  • 1
    Isn’t it a locale problem? Your string is in English, so if your default locale isn’t, it will likely cause parsing to fail. Does `DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss z yyyy").withLocale(Locale.ROOT)` work for you? Similar: [java DateTimeFormatterBuilder fails on testtime \[duplicate\]](https://stackoverflow.com/questions/50526234/java-datetimeformatterbuilder-fails-on-testtime). – Ole V.V. Jul 29 '22 at 16:41
  • 3
    Please, except if for use with a legacy API that you cannot change, do not create a `java.util.Date`. It’s for your own sake. That class is so poorly designed, nothing we want to deal with. Either stick with Joda-Time or follow the official Joda-Time recommendation and migrate to java.time. – Ole V.V. Jul 29 '22 at 16:46
  • Similar: [Joda-Time invalid format \[duplicate\]](https://stackoverflow.com/questions/35086527/joda-time-invalid-format). Unfortunately that one is unanswered. – Ole V.V. Jul 30 '22 at 09:03

1 Answers1

0

You can use a code like this :

String time = "Fri Jul 29 12:56:35 UTC 2022";
Date date = new Date(time);
long millis = date.getTime();
System.out.println(millis);