Back

Comparing Dates in Velocity

Description

This code sample will help you learn different ways to obtain today's date and format it. It also shows how you can compare two dates, or one content date with today's date.

When comparing dates in Velocity it's helpful to use Velocity's Date Tool:
http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/DateTool.html

Once a Date is converted to a Java Calendar you can use the compareTo method to compare two dates:
http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html

Code

##Today's Date
$date.format('yyyyMMdd',$date)
$date = Apr 19, 2024, 10:10:56 AM                         
$date.long = April 19, 2024 at 10:10:56 AM EDT                    
$date.medium_time = 10:10:56 AM            
$date.full_date = Friday, April 19, 2024               
$date.get('default','short') = Apr 19, 2024, 10:10 AM  
$date.get('yyyy-M-d H:m:s') = 2024-4-19 10:10:56  

#foreach($con in $dotcontent.pull("+structureName:TestDates",10,"modDate desc"))
$con.title
#set($strDate1=$date.format('MM/dd/yyyy hh:mm:ss a',$con.date1))
#set($strDate2=$date.format('MM/dd/yyyy hh:mm:ss a',$con.date2))
Date1=$strDate1
Date2=$strDate2

#set($cal1=$date.toCalendar($con.date1))
#set($cal2=$date.toCalendar($con.date2))
#set($calToday=$date.toCalendar($date))
#set($calCompare=$cal1.compareTo($cal2))
#set($cal1CompareToday=$cal1.compareTo($calToday))
#set($cal2CompareToday=$cal2.compareTo($calToday))

#if($calCompare==0)
$strDate1 equals $strDate2
#elseif($calCompare>0)
$strDate1 is greater than $strDate2
#else
$strDate1 is less than $strDate2
#end

#if($cal1CompareToday>0)
$strDate1 is in the future
#else
$strDate1 is in the past
#end

#if($cal2CompareToday>0)
$strDate2 is in the future
#else
$strDate2 is in the past
#end

#end