DEV Community

ouryperd
ouryperd

Posted on

Neat time and date manipulation with Groovy

You can use TimeCategory for simple offset calculations:

import groovy.time.TimeCategory

use( TimeCategory ) {
    twelveSecondsLater = new Date() + 12.seconds
    twelveSecondsAgo = new Date() - 12.seconds
    oneMinuteLater = new Date() + 1.hours
    oneMinuteAgo = new Date() - 1.hours
    halfAnHourLater = new Date() + 30.minutes
    halfAnHourAgo = new Date() - 30.minutes
    twoHoursLater = new Date() + 2.hours
    twoHoursAgo = new Date() - 2.hours
    fiveDaysLater = new Date() + 5.days
    fiveDaysAgo = new Date() - 5.days
    oneWeekLater = new Date() + 1.weeks
    oneWeekAgo = new Date() - 1.weeks
    oneMonthLater = new Date() + 1.months
    oneMonthAgo = new Date() - 1.months
    oneYearLater = new Date() + 1.years
    oneYearAgo = new Date() - 1.years
}

println twelveSecondsLater.format("yyyy-MM-dd HH.mm.ss")
println twelveSecondsAgo.format("yyyy-MM-dd HH.mm.ss")
println oneMinuteLater.format("yyyy-MM-dd HH.mm.ss")
println oneMinuteAgo.format("yyyy-MM-dd HH.mm.ss")
println halfAnHourLater.format("yyyy-MM-dd HH.mm")
println halfAnHourAgo.format("yyyy-MM-dd HH.mm")
println twoHoursLater.format("yyyy-MM-dd HH.mm")
println twoHoursAgo.format("yyyy-MM-dd HH.mm")
println fiveDaysLater.format("yyyy-MM-dd")
println fiveDaysAgo.format("yyyy-MM-dd")
println oneWeekLater.format("yyyy-MM-dd")
println oneWeekAgo.format("yyyy-MM-dd")
println oneMonthLater.format("yyyy-MM-dd")
println oneMonthAgo.format("yyyy-MM-dd")
println oneYearLater.format("yyyy-MM-dd")
println oneYearAgo.format("yyyy-MM-dd")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)