user3624378
user3624378

Reputation: 417

SoapUI and problem with Groovy Convert date to yyyy-MM-dd

I've used this to add days to date and then format date to yyyy-MM-dd. But since new SoapUI version, this no longer work.

import static java.util.Calendar.*

String myOrderDate(int nrOfDays){ 
    def date = new Date()
    def datePlus = date.clone()
    datePlus = datePlus + nrOfDays
    return datePlus.format('YYYY-MM-dd')
}

Instead I get stacktrace:

groovy.lang.MissingMethodException: No signature of method: java.util.Date.plus() is applicable for argument types: (Integer)

What am I doing wrong?

Upvotes: 1

Views: 289

Answers (2)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27245

The code you have will work fine if you add a dependency on groovy-dateutil.

See the project at https://github.com/jeffbrown/groovydate.

At lib/src/main/groovy/groovydate/Library.groovy is your method copied and pasted as is.

package groovydate

class Library {
    String myOrderDate(int nrOfDays) {
        def date = new Date()
        def datePlus = date.clone()
        datePlus = datePlus + nrOfDays
        return datePlus.format('YYYY-MM-dd')
    }
}

The test at lib/src/test/groovy/groovydate/LibraryTest.groovy passes:

package groovydate

import spock.lang.Specification

class LibraryTest extends Specification {
    def "test order date"() {
        given:
        def lib = new Library()

        when:
        lib.myOrderDate(4)

        then:
        noExceptionThrown()
    }
}

That only works because of the dependency expressed at lib/build.gradle#L36

implementation 'org.codehaus.groovy:groovy-dateutil:3.0.9'

Without dateutil, the runtime will complain about the missing method because it isn't there without the missing dependency.

Upvotes: 1

user987339
user987339

Reputation: 10707

Use public Date plus(int days):

import static java.util.Calendar.*

String myOrderDate(int nrOfDays){ 
    def date = new Date()
    def datePlus = date.clone()
    datePlus = datePlus.plus(nrOfDays)
    return datePlus.format('YYYY-MM-dd')
}

And you can do it shorter:

import static java.util.Calendar.*

String myOrderDate(int nrOfDays){ 
    def date = new Date()
    return date.plus(nrOfDays).format('YYYY-MM-dd')
}

Since there is an issue with importing libraries, maybe you should stick with Java way. Try following code:

import java.time.LocalDate
import java.time.format.DateTimeFormatter
    
String myOrderDate(int nrOfDays){ 
        def date = LocalDate.now().plusDays(nrOfDays)
        return date.format(DateTimeFormatter.ofPattern(('YYYY-MM-dd')))
}

Upvotes: 0

Related Questions