Date and Time Basics: dateAdd() and dateDiff()
Adding dates and time is very easy in ColdFusion. The dateAdd() function makes adding a span of time to a date extremely simple. The dateDiff() function makes finding a time span also very easy. ColdFusion works with date / time objects. A date time object contains a date and time. The two functions talked about in this tutorial can work with a variety of date / time measurements from milliseconds to years.
Adding Time to an Existing Date
Adding a specified amount of time to an existing date is easy using the dateAdd() function built into ColdFusion.
The dateAdd() function takes three arguments: datepart, number and date.
The datepart is the measurement of time that we want to use. Valid values for datepart are
· yyyy: Year
· q: Quarter
· m: Month
· y: Day of year
· d: Day
· w: Weekday
· ww: Week
· h: Hour
· n: Minute
· s: Second
· l: Millisecond
The second argument, 'number' is how many units of 'datepart' that we want to add to the 'date' argument. Negative numbers go to the past, positive numbers go to the future
For these examples, the now() function will be used to give the current date and time. To add 3 days to todays date, simply do the following:
<cfoutput>
#dateAdd("d",3,now())#
</cfoutput>
Run this in a cfml template and you will see that it displays the date 3 days from the time the script is ran. Changing the 3 to a -3 would show you the date 3 days past.
Time Between Two Dates
DateDiff() can be used to find the amount of time between two dates as an integer. The function takes three arguments: datepart, date1 and date2.
Valid values for datepart are:
· yyyy: Years
· q: Quarters
· m: Months
· y: Days of year (same as d)
· d: Days
· w: Weekdays (same as ww)
· ww: Weeks
· h: Hours
· n: Minutes
· s: Seconds
DateDiff() finds how many datepart units less date1 is from date2. It returns an integer as the amount of whole datepart units between the dates.
<cfoutput>
#dateDiff("m","01/01/2000","01/29/2001")#
</cfoutput>
The value should be 12. There are only 11 whole months from January 1st 2000, and January 29th 2001.
Change the script to return days
<cfoutput>
#dateDiff("d","01/01/2000","12/29/2000")#
</cfoutput>
You should get 363. There are 363 days between these dates.
Try it again with years
<cfoutput>
#dateDiff("yyyy","01/01/2000","01/29/2001")#
</cfoutput>
You will get a result of 0, which is correct. There are no full years between these dates.
That is the basics to calculating dates in ColdFusion. It is really quite simple to start out. Of course there are several other functions in ColdFusion specifically for working with dates and times including createDate(), dateCompare(), and many more.
____________
Comments
Kent
04/12/2006
Im back,
I created a date calculator and see here http://www.ktaisia.com/test/getTuesday.cfm but this is fixed to "Tuesday", I see your codes are good and you have more experience. I was wondering if you could modify it to take any day.