'Problem when string date to Date format in groovy:

I'm trying to compare a String with a date in it with the current date, but when I try to parse the string to date format it always give me an error.

the part of code that gives problem:

String data = "12-05-2020"
Date teste = Date.parse("dd-MM-yyy",data)

the error:

groovy.lang.MissingMethodException: No signature of method: static java.util.Date.parse() is applicable for argument types: (String, String) values: [dd-MM-yyy, 12-05-2020]
Possible solutions: parse(java.lang.String), wait(), clone(), grep(), any(), putAt(java.lang.String, java.lang.Object)
    at Script1.run(Script1.groovy:2)

It seems to be something very silly, so, if you could help me! Thanks a lot



Solution 1:[1]

Since Groovy 2.5 (I think), the standard Java Date extensions have not been shipped with the groovy-all jar

If you have to use them, you'll need to include another dependency

org.codehaus.groovy:groovy-dateutil:«version»

(where «version» is the same as the version of Groovy you're using)

The reason for it's removal is that there are new (much better) Date Time classes in the java.time package...

So you can do the following in it's place:

import java.time.LocalDate

String data = "12-05-2020"
LocalDate teste = LocalDate.parse(data, "dd-MM-yyyy")

Without needing the extra library

Solution 2:[2]

Argument data types mismatch

The error message told you exactly what is wrong:

No signature of method: static java.util.Date.parse() is applicable for argument types: (String, String)

There is no such method on that class taking a pair of String objects.

Instead, you should be using:

  • java.time classes only. Never use the terrible date-time classes such as Date and Calendar. Those legacy classes were entirely supplanted by java.time with the adoption of JSR 310 years ago.
  • DateTimeFormatter to specify a custom formatting pattern.

Another problem: Your formatting pattern had only here y where it needed four. Also, in java.time, you can use uuuu rather than yyyy (though it makes no difference for contemporary dates).

In Java syntax (I do not know Groovy):

String input = "12-05-2020" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
LocalDate teste = LocalDate.parse( input , f ) ;

Solution 3:[3]

I was having the same problem running a groovy script from eclipse 2022-03 (4.23.0) with the groovy plugin. I got around it by adding groovy-dateutil-.jar to the run>Run Configurations...>Dependencies Tab>Classpath Entries

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Mauro Zallocco