Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem when string date to Date format in groovy:

Tags:

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

like image 658
19jmrs Avatar asked Apr 15 '26 06:04

19jmrs


2 Answers

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

like image 71
tim_yates Avatar answered Apr 18 '26 23:04

tim_yates


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 ) ;
like image 24
Basil Bourque Avatar answered Apr 19 '26 01:04

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!