Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date time in Groovy

Tags:

groovy

soapui

I'm looking to add 1 second to a datetime so I can test date based pagination. I'm hoping get a date from our API response, convert the date string into a date, then convert that into milliseconds, add a second and then convert back into a datestring and use it in my next API request. ( sound longwinded? It sure feels like it is!)

I'm having and issue when I try to parse a dateTime. The following code is throwing an error:

def c= new date().parse("yyyy-mm-ddThh:mm:ss",lastDate)
log.info "new formatt"+lastDate
log.info c.timeInMillis

Error: groovy.lang.MissingMethodException: No signature of method: java.util.Date.parse() is applicable for argument types: (java.lang.String, groovy.util.slurpersupport.NodeChildren) values: [yyyy-mm-ddThh:mm:ss, 2007-01-26T00:00:00] Possible solutions: parse(java.lang.String), parse(java.lang.String, java.lang.String), wait(), clone(), any(), use(java.util.List, groovy.lang.Closure)

Any tips on how to achieve my goal? Or is it a dimwit approach?

like image 668
Richard Fortune Avatar asked Nov 17 '10 02:11

Richard Fortune


2 Answers

Sounds like quite a round about way of adding a second. Why not just:

import groovy.time.TimeCategory

def lastDate = new Date()

use(TimeCategory) {
    lastDate = lastDate + 1.second
}

For more flexible date string parsing, you might want to look at the JChronic java library. It can handle dates in many different formats and doesn't rely on having an exact template like the SimpleDateFormat class. Here's an example using both of these:

Date.metaClass.'static'.fromString = { str ->
    com.mdimension.jchronic.Chronic.parse(str).beginCalendar.time
}

def lastDate = Date.fromString("2007-01-26T00:00:00")

use (TimeCategory) {
    100.times {
        runTest(lastDate)
        lastDate = lastDate + 1.second
    }
}
like image 94
ataylor Avatar answered Sep 28 '22 18:09

ataylor


Probably the most consise, idiomatic groovy solution without dependencies:

Date.parse( "yyyy-MM-dd'T'HH:mm:ss", text ).with { new Date( time + 1000) }
like image 30
btiernay Avatar answered Sep 28 '22 19:09

btiernay