Grails Cookbook - A collection of tutorials and examples

Groovy Date Remove Or Clear Time Component

When we are comparing Date instances, we usually just care about the date part and not the time component. For more accurate comparison, it is sometimes desirable to remove the time component from a Date object. Below is an example on how to remove or clear time component from a Date instance in Groovy.

Here is a simple example that prints a date object that has a time component. And it also prints the same date without time component.

package gtest
 * A simple Groovy example that removes time component from a date.
class Test {
  public static void main(String[] args) {
    def currentDate = new Date()
    println "Current date = ${currentDate}"
    println "Current date without time = ${currentDate}"

From the code above, using the clearTime() method in Groovy removes the time component from a Date. This is done by setting all time related component to zero. The date object state is altered. Below is the output of the code above.
Current date = Mon Jun 20 20:40:42 SGT 2016
Current date without time = Mon Jun 20 00:00:00 SGT 201