It's common in every programming language or application development used to add or subtract date and time, so Groovy has built-in class TimeCategory that can use for add or subtract date time. Using TimeCategory make DateTime manipulation simpler than using regular Java time/date API. Like the previous tutorial, we will use web Groovy executor to run our Groovy codes.
Open your browser and go to Groovy Console. Next, just paste your code inside code box then click execute.
Add/Subtract Date Time
1. Example of Add Time 10 hours from now
use (groovy.time.TimeCategory) {
println new Date()
println 10.hours.from.now
}
Output:
Thu Mar 16 04:38:29 UTC 2017
Thu Mar 16 14:38:29 UTC 2017
2. Example of Add Time 15 minutes from now
use (groovy.time.TimeCategory) {
println new Date()
println 15.minutes.from.now
}
Output:
Thu Mar 16 04:45:30 UTC 2017
Thu Mar 16 05:00:30 UTC 2017
3. Example of Subtract Time 10 minutes from now
use (groovy.time.TimeCategory) {
def date = new Date()
println date
println date-15.minutes
}
Output:
Thu Mar 16 04:49:19 UTC 2017
Thu Mar 16 04:34:19 UTC 2017
4. Example of Subtract Time 45 hours from now
use (groovy.time.TimeCategory) {
def date = new Date()
println date
println date-45.hours
}
Output:
Thu Mar 16 04:50:55 UTC 2017
Tue Mar 14 07:50:55 UTC 2017
5. Example of Add Date 20 days from now
use (groovy.time.TimeCategory) {
println new Date()
println 20.days.from.now
}
Output:
Thu Mar 16 04:54:12 UTC 2017
Wed Apr 05 00:00:00 UTC 2017
6. Example of Add Date 3 months from now
use (groovy.time.TimeCategory) {
println new Date()
println 3.months.from.now
}
Output:
Thu Mar 16 04:55:25 UTC 2017
Fri Jun 16 00:00:00 UTC 2017
7. Example of Add Date 2 years from now
use (groovy.time.TimeCategory) {
println new Date()
println 2.years.from.now
}
Output:
Thu Mar 16 04:56:51 UTC 2017
Sat Mar 16 00:00:00 UTC 2019
8. Example of Subtract Date 10 days from now
use (groovy.time.TimeCategory) {
def date = new Date()
println date
println date-10.days
}
Output:
Thu Mar 16 04:58:11 UTC 2017
Mon Mar 06 04:58:11 UTC 2017
9. Example of Subtract Date 3 weeks from now
use (groovy.time.TimeCategory) {
def date = new Date()
println date
println date-3.weeks
}
Output:
Thu Mar 16 04:58:11 UTC 2017
Mon Mar 06 04:58:11 UTC 2017
That it's for now, the simple examples of add or subtract date time in Groovy.
That just the basic. If you need more deep learning about Groovy and Grails you can take the following cheap course:
Thanks.