Groovy: Add or Subtract Date Time Using TimeCategory

by Didin J. on Mar 17, 2017 Groovy: Add or Subtract Date Time Using TimeCategory

The examples of using Groovy language for add and subtract date time using built in TimeCategory class.

It's common in every programming language or application development use add or subtract date and time, so Groovy has built-in class TimeCategory that can use for add or subtract date time. As 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.


1. Add/Subtract Date Time

1.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

1.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

1.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

1.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

 

1.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

1.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

1.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

 

1.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

1.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.

Thanks.

The following resources might be useful for you:

Loading…