- CFML Reference User Guide
- ColdFusion functions
- ColdFusion functions by category
- Functions a-b
- Abs
- ACos
- AddSOAPRequestHeader
- AddSOAPResponseHeader
- AjaxLink
- AjaxOnLoad
- ApplicationStop
- ArrayAppend
- ArrayAvg
- ArrayClear
- ArrayContains
- ArrayContainsNoCase
- ArrayDelete
- ArrayDeleteAt
- ArrayDeleteNoCase
- ArrayEach
- ArrayFilter
- ArrayFind
- ArrayFindAll
- ArrayFindAllNoCase
- ArrayFindNoCase
- ArrayInsertAt
- ArrayIsDefined
- ArrayIsEmpty
- ArrayLen
- ArrayMap
- ArrayMax
- ArrayMin
- ArrayNew
- ArrayPrepend
- ArrayReduce
- ArrayResize
- ArraySet
- ArraySetMetadata
- ArraySlice
- ArraySort
- ArraySum
- ArraySwap
- ArrayToList
- Asc
- ASin
- Atn
- AuthenticatedContext
- AuthenticatedUser
- BinaryDecode
- BinaryEncode
- BitAnd
- BitMaskClear
- BitMaskRead
- BitMaskSet
- BitNot
- BitOr
- BitSHLN
- BitSHRN
- BitXor
- BooleanFormat
- Abs
- Functions-c-d
- CacheGet
- CacheGetAllIds
- CacheGetMetadata
- CacheGetProperties
- CacheGetSession
- CacheIdExists
- CachePut
- CacheRegionExists
- CacheRegionNew
- CacheRegionRemove
- CacheRemove
- CacheRemoveAll
- CacheSetProperties
- CallStackDump
- CallStackGet
- CanDeSerialize
- Canonicalize
- CanSerialize
- Ceiling
- CharsetDecode
- CharsetEncode
- Chr
- CJustify
- Compare
- CompareNoCase
- Cos
- CreateDate
- CreateDateTime
- CreateObject
- CreateObject: .NET object
- CreateObject: COM object
- CreateObject: component object
- CreateObject: CORBA object
- CreateObject: Java or EJB object
- CreateObject: web service object
- CreateODBCDate
- CreateODBCDateTime
- CreateODBCTime
- CreateSignedJWT
- CreateEncryptedJWT
- CreateTime
- CreateTimeSpan
- CreateUUID
- CSRFGenerateToken
- CSRFVerifyToken
- CSVRead
- CSVWrite
- CSVProcess
- DateAdd
- DateCompare
- DateConvert
- DateDiff
- DateFormat
- DatePart
- DateTimeFormat
- Day
- DayOfWeek
- DayOfWeekAsString
- DayOfYear
- DaysInMonth
- DaysInYear
- DE
- DecimalFormat
- DecodeForHTML
- DecodeFromURL
- DecrementValue
- Decrypt
- DecryptBinary
- DeleteClientVariable
- Deserialize
- DeserializeJSON
- DeserializeXML
- DirectoryCopy
- DirectoryCreate
- DirectoryDelete
- DirectoryExists
- DirectoryList
- DirectoryRename
- DollarFormat
- DotNetToCFType
- Duplicate
- Functions-e-g
- EncodeForCSS
- EncodeForDN
- EncodeForHTML
- EncodeForHTMLAttribute
- EncodeForJavaScript
- EncodeForLDAP
- EncodeForURL
- EncodeForXML
- EncodeForXMLAttribute
- EncodeForXpath
- Encrypt
- EncryptBinary
- EntityDelete
- EntityLoad
- EntityLoadByExample
- EntityLoadByPK
- EntityMerge
- EntityNew
- EntityReload
- EntitySave
- EntityToQuery
- Evaluate
- Exp
- ExpandPath
- FileClose
- FileCopy
- FileDelete
- FileExists
- FileGetMimeType
- FileIsEOF
- FileMove
- FileOpen
- FileRead
- FileReadBinary
- FileReadLine
- FileSeek
- FileSetAccessMode
- FileSetAttribute
- FileSetLastModified
- FileSkipBytes
- FileUpload
- FileUploadAll
- FileWrite
- FileWriteLine
- Find
- FindNoCase
- FindOneOf
- FirstDayOfMonth
- Fix
- Floor
- FormatBaseN
- GeneratePBKDFKey
- GenerateSecretKey
- GetApplicationMetadata
- GetAuthUser
- GetBaseTagData
- GetBaseTagList
- GetBaseTemplatePath
- GetClientVariablesList
- GetComponentMetaData
- GetContextRoot
- GetCPUUsage
- GetCurrentTemplatePath
- GetCSPNonce
- GetDirectoryFromPath
- GetEncoding
- GetException
- GetFileFromPath
- GetFileInfo
- GetFreeSpace
- GetFunctionCalledName
- GetFunctionList
- GetGatewayHelper
- GetHttpRequestData
- GetHttpTimeString
- GetK2ServerDocCount
- GetK2ServerDocCountLimit
- GetLocale
- GetLocaleDisplayName
- GetLocalHostIP
- GetMetaData
- GetMetricData
- GetPageContext
- GetPropertyString
- GetPropertyFile
- GetPrinterInfo
- GetPrinterList
- GetProfileSections
- GetProfileString
- GetReadableImageFormats
- GetSafeHTML
- GetSAMLAuthRequest
- GetSAMLLogoutRequest
- Generate3DesKey
- GenerateSAMLSPMetadata
- GetSOAPRequest
- GetSOAPRequestHeader
- GetSOAPResponse
- GetSOAPResponseHeader
- GetSystemFreeMemory
- GetSystemTotalMemory
- GetTempDirectory
- GetTempFile
- GetTemplatePath
- GetTickCount
- GetTimeZoneInfo
- GetToken
- GetTotalSpace
- GetUserRoles
- GetVFSMetaData
- GetWriteableImageFormats
- Functions-h-im
- Hash
- HMac
- Hour
- HQLMethods
- HTMLCodeFormat
- HTMLEditFormat
- IIf
- ImageAddBorder
- ImageBlur
- ImageClearRect
- ImageCopy
- ImageCreateCaptcha
- ImageCrop
- ImageDrawArc
- ImageDrawBeveledRect
- ImageDrawCubicCurve
- ImageDrawLine
- ImageDrawLines
- ImageDrawOval
- ImageDrawPoint
- ImageDrawQuadraticCurve
- ImageDrawRect
- ImageDrawRoundRect
- ImageDrawText
- ImageFlip
- ImageGetBlob
- ImageGetBufferedImage
- ImageGetEXIFMetadata
- ImageGetEXIFTag
- ImageGetHeight
- ImageGetIPTCMetadata
- ImageGetIPTCTag
- ImageGetMetadata
- ImageGetWidth
- ImageGrayscale
- ImageInfo
- ImageMakeColorTransparent
- ImageMakeTranslucent
- ImageNegative
- ImageNew
- ImageOverlay
- ImagePaste
- ImageRead
- ImageReadBase64
- ImageResize
- ImageRotate
- ImageRotateDrawingAxis
- ImageScaleToFit
- ImageSetAntialiasing
- ImageSetBackgroundColor
- ImageSetDrawingColor
- ImageSetDrawingStroke
- ImageSetDrawingTransparency
- ImageSharpen
- ImageShear
- ImageShearDrawingAxis
- ImageTranslate
- ImageTranslateDrawingAxis
- ImageWrite
- ImageWriteBase64
- ImageXORDrawingMode
- Functions-in-k
- IncrementValue
- InputBaseN
- Insert
- Int
- InterruptThread
- InvalidateOauthAccesstoken
- Invoke
- InitSAMLAuthRequest
- InitSAMLLogoutRequest
- InvokeCFClientFunction
- IsArray
- IsAuthenticated
- IsAuthorized
- IsBinary
- IsBoolean
- IsClosure
- IsCustomFunction
- IsDate
- IsDateObject
- IsDDX
- IsDebugMode
- IsDefined
- IsImage
- IsImageFile
- IsInstanceOf
- IsIPv6
- IsJSON
- IsK2ServerABroker
- IsK2ServerDocCountExceeded
- IsK2ServerOnline
- IsLeapYear
- IsLocalHost
- IsNull
- IsNumeric
- IsNumericDate
- IsObject
- isOnline
- IsPDFArchive
- IsPDFFile
- IsPDFObject
- IsProtected
- IsQuery
- isSamlLogoutResponse
- isSafeHTML
- IsSimpleValue
- IsSOAPRequest
- IsSpreadsheetFile
- IsSpreadsheetObject
- IsStruct
- isThreadInterrupted
- IsUserInAnyRole
- IsUserInRole
- IsUserLoggedIn
- IsValid
- IsValidOauthAccesstoken
- IsWDDX
- IsXML
- IsXmlAttribute
- IsXmlDoc
- IsXmlElem
- IsXmlNode
- IsXmlRoot
- JavaCast
- JSStringFormat
- Functions-l
- LCase
- Left
- Len
- ListAppend
- ListChangeDelims
- ListContains
- ListContainsNoCase
- ListDeleteAt
- ListEach
- ListFilter
- ListFind
- ListFindNoCase
- ListFirst
- ListGetAt
- ListGetDuplicates
- ListInsertAt
- ListLast
- ListLen
- ListMap
- ListPrepend
- ListQualify
- ListReduce
- ListRemoveDuplicates
- ListRest
- ListSetAt
- ListSort
- ListToArray
- ListValueCount
- ListValueCountNoCase
- LJustify
- Location
- Log
- Log10
- LSCurrencyFormat
- LSDateFormat
- LSDateTimeFormat
- LSEuroCurrencyFormat
- LSIsCurrency
- LSIsDate
- LSIsNumeric
- LSNumberFormat
- LSParseCurrency
- LSParseDateTime
- LSParseEuroCurrency
- LSParseNumber
- LSTimeFormat
- LTrim
- Functions-m-r
- Max
- Mid
- Min
- Minute
- Month
- MonthAsString
- Now
- NumberFormat
- ObjectEquals
- ObjectLoad
- ObjectSave
- OnWSAuthenticate
- ORMClearSession
- ORMCloseAllSessions
- ORMCloseSession
- ORMEvictCollection
- ORMEvictEntity
- ORMEvictQueries
- ORMExecuteQuery
- ORMFlush
- ORMFlushall
- ORMGetSession
- ORMGetSessionFactory
- ORMIndex
- ORMIndexPurge
- ORMReload
- ORMSearch
- ORMSearchOffline
- ParagraphFormat
- ParameterExists
- ParseDateTime
- Pi
- PrecisionEvaluate
- ProcessSAMLResponse
- ProcessSAMLLogoutRequest
- Quarter
- PreserveSingleQuotes
- QueryAddColumn
- QueryAddRow
- QueryConvertForGrid
- QueryExecute
- QueryFilter
- QueryGetResult
- QueryGetRow
- QueryKeyExists
- QueryMap
- QueryNew
- QueryReduce
- QuerySetCell
- QuotedValueList
- QueryEach
- Rand
- Randomize
- RandRange
- ReEscape
- REFind
- REFindNoCase
- ReleaseComObject
- REMatch
- REMatchNoCase
- RemoveCachedQuery
- RemoveChars
- RepeatString
- Replace
- ReplaceList
- ReplaceNoCase
- REReplace
- REReplaceNoCase
- RestDeleteApplication
- RestSetResponse
- RestInitApplication
- Reverse
- Right
- RJustify
- Round
- RTrim
- Functions-s
- Second
- SendGatewayMessage
- SendSAMLLogoutResponse
- Serialize
- SerializeJSON
- SerializeXML
- SessionInvalidate
- SessionRotate
- SessionGetMetaData
- SessionInvalidate
- SessionRotate
- SetDay
- SetEncoding
- SetHour
- SetLocale
- SetMonth
- SetProfileString
- SetPropertyString
- SetVariable
- SetYear
- Sgn
- Sin
- Sleep
- SpanExcluding
- SpanIncluding
- SpreadsheetAddAutoFilter
- SpreadsheetAddColumn
- SpreadsheetAddFreezePane
- SpreadsheetAddImage
- SpreadsheetAddInfo
- SpreadsheetAddPageBreaks
- SpreadsheetAddRow
- SpreadsheetAddRows
- SpreadsheetAddSplitPane
- SpreadsheetCreateSheet
- SpreadsheetDeleteColumn
- SpreadsheetDeleteColumns
- SpreadsheetDeleteRow
- SpreadsheetDeleteRows
- SpreadsheetFormatCell
- SpreadsheetFormatColumn
- SpreadsheetFormatCellRange
- SpreadsheetFormatColumn
- SpreadsheetFormatColumns
- SpreadsheetFormatRow
- SpreadsheetFormatRows
- SpreadsheetGetCellComment
- SpreadsheetGetCellFormula
- SpreadsheetGetCellValue
- SpreadsheetGetColumnCount
- SpreadsheetInfo
- SpreadsheetMergeCells
- SpreadsheetNew
- SpreadsheetRead
- SpreadsheetReadBinary
- SpreadsheetRemoveSheet
- SpreadsheetSetActiveSheet
- SpreadsheetSetActiveSheetNumber
- SpreadsheetSetCellComment
- SpreadsheetSetCellFormula
- SpreadsheetSetCellValue
- SpreadsheetSetColumnWidth
- SpreadsheetSetFooter
- SpreadsheetSetHeader
- SpreadsheetSetRowHeight
- SpreadsheetShiftColumns
- SpreadsheetShiftRows
- SpreadsheetWrite
- StreamingSpreadsheetNew
- StreamingSpreadsheetCleanup
- StreamingSpreadsheetRead
- StreamingSpreadsheetProcess
- SpreadsheetSetFooterImage
- SpreadsheetSetHeaderImage
- SpreadsheetSetFittoPage
- SpreadsheetUngroupColumns
- SpreadsheetGroupColumns
- SpreadsheetUngroupRows
- SpreadsheetGroupRows
- SpreadsheetRemoveColumnBreak
- SpreadsheetSetColumnBreak
- SpreadsheetRemoveRowBreak
- SpreadsheetSetRowBreak
- SpreadsheetRemovePrintGridlines
- SpreadsheetAddPrintGridlines
- SpreadsheetGetColumnWidth
- SpreadsheetSetColumnHidden
- SpreadsheetSetRowHidden
- SpreadsheetisColumnHidden
- SpreadsheetisRowHidden
- SpreadsheetisStreamingXmlFormat
- SpreadsheetisXmlFormat
- SpreadsheetisBinaryFormat
- SpreadsheetRenameSheet
- SpreadsheetRemoveSheetNumber
- SpreadsheetGetLastRowNumber
- SpreadsheetGetPrintOrientation
- Sqr
- StripCR
- StructAppend
- StructClear
- StructCopy
- StructCount
- StructDelete
- StructEach
- StructFilter
- StructFind
- StructFindKey
- StructFindValue
- StructGet
- StructGetMetadata
- StructInsert
- StructIsEmpty
- StructKeyArray
- StructKeyExists
- StructKeyList
- StructMap
- StructNew
- StructReduce
- StructSetMetadata
- StructSort
- StructToSorted
- StructUpdate
- StructValueArray
- StoreSetMetadata
- StoreGetACL
- StoreGetMetadata
- StoreAddACL
- StoreSetACL
- Functions-t-z
- Tan
- ThreadJoin
- ThreadTerminate
- Throw
- TimeFormat
- ToBase64
- ToBinary
- ToScript
- ToString
- Trace
- Transactionandconcurrency
- TransactionCommit
- TransactionRollback
- TransactionSetSavePoint
- Trim
- UCase
- URLDecode
- URLEncodedFormat
- URLSessionFormat
- Val
- ValueList
- VerifyClient
- Week
- Wrap
- WriteDump
- WriteLog
- WriteOutput
- WSGetAllChannels
- WSGetSubscribers
- WSPublish
- WSSendMessage
- XmlChildPos
- XmlElemNew
- XmlFormat
- XmlGetNodeType
- XmlNew
- XmlParse
- XmlSearch
- XmlTransform
- XmlValidate
- Year
- YesNoFormat
- ColdFusion tags
- ColdFusion tag summary
- ColdFusion tags by category
- Application framework tags
- Communications tags
- Database manipulation tags
- Data output tags
- Debugging tags
- Exception handling tags
- Extensibility tags
- File management tags
- Flow-control tags
- Forms tags
- Internet Protocol tags
- Page processing tags
- Security tags
- Variable manipulation tags
- Other tags
- Tags a-b
- Tags c
- cfcache
- cfcalendar
- cfcase
- cfcatch
- cfchart
- cfchart tag in ColdFusion
- Get started with cfchart
- Customize a chart using cfchart
- Advanced cfchart customization options
- Create an area chart in ColdFusion
- Create line charts in ColdFusion
- Create bar charts in ColdFusion
- Create floating bar charts in ColdFusion
- Create histograms in ColdFusion
- Create pie charts in ColdFusion
- Create funnel charts in ColdFusion
- Create pyramid charts in ColdFusion
- Create curve charts in ColdFusion
- Create boxplots in ColdFusion
- Create donut charts in ColdFusion
- Create bubble charts in ColdFusion
- Create scatterplots in ColdFusion
- Create radar charts in ColdFusion
- Other chart types in ColdFusion (Cone, Cylinder, Piano, and Bullet)
- Advanced customization options in cfchart
- cfchartdata
- cfchartseries
- cfchartset
- cfclient
- cfclientsettings
- cfcol
- cfcollection
- cfcomponent
- cfcontent
- cfcontinue
- cfcookie
- Tags f
- cffeed
- cffile
- cffile action = "append"
- cffile action = "copy"
- cffile action = "delete"
- cffile action = "move"
- cffile action = "read"
- cffile action = "readBinary"
- cffile action = "rename"
- cffile action = "upload"
- cffile action = "uploadAll"
- cffile action = "write"
- cffileupload
- cffinally
- cfflush
- cfform
- cfformgroup
- cfformitem
- cfftp
- cfftp: Connection: file and directory operations
- cfftp: Opening and closing FTP server connections
- cfftp : Opening and closing secure FTP server connections
- cfftp action = "listDir"
- cffunction
- Tags g-h
- Tags i
- Tags j-l
- cfjava
- cflayout
- cflayoutarea
- cfldap
- cflocation
- cflock
- cflog
- cflogin
- cfloginuser
- cflogout
- cfloop
- cfloop : conditional loop
- cfloop : index loop
- cfloop : looping over a COM collection or structure
- cfloop : looping over a date or time range
- cfloop : looping over a list, a file, or an array
- cfloop : looping over a query
- Tags m-o
- cfmail
- cfmailparam
- cfmailpart
- cfmap
- cfmapitem
- cfmediaplayer
- cfmenu
- cfmenuitem
- cfmessagebox
- cfmodule
- cfNTauthenticate
- cfoauth
- cfobject
- cfobject: .NET object
- cfobject: COM object
- cfobject: component object
- cfobject: CORBA object
- cfobject: Java or EJB object
- cfobject: web service object
- cfobjectcache
- cfoutput
- Tags p-q
- Tags r-s
- Tags t
- Tags u-z
- CFML Reference
- Reserved words and variables
- Ajax JavaScript functions
- Ajax JavaScript functions
- Function summary Ajax
- ColdFusion.Ajax.submitForm
- ColdFusion.Autosuggest.getAutosuggestObject
- ColdFusion.Layout.enableSourceBind
- ColdFusion.MessageBox.getMessageBoxObject
- ColdFusion.ProgressBar.getProgressBarObject
- ColdFusion.MessageBox.isMessageBoxDefined
- JavaScriptFunctionsinColdFusion9Update1
- ColdFusion ActionScript functions
- ColdFusion mobile functions
- Application.cfc reference
- Script functions implemented as CFCs
- ColdFusion Flash Form style reference
- Styles valid for all controls
- Styles for cfform
- Styles for cfformgroup with horizontal or vertical type attributes
- Styles for box-style cfformgroup elements
- Styles for cfformgroup with accordion type attribute
- Styles for cfformgroup with tabnavigator type attribute
- Styles for cfformitem with hrule or vrule type attributes
- Styles for cfinput with radio, checkbox, button, image, or submit type attributes
- Styles for cftextarea tag and cfinput with text, password, or hidden type attributes
- Styles for cfselect with size attribute value of 1
- Styles for cfselect with size attribute value greater than 1
- Styles for cfcalendar tag and cfinput with dateField type attribute
- Styles for the cfgrid tag
- Styles for the cftree tag
- ColdFusion Flash Form Style Reference
- ColdFusion event gateway reference
- ColdFusion Event Gateway reference
- addEvent
- CFEvent
- CFEventclass
- Constructor
- Gateway development interfaces and classes
- getStatus
- setCFCPath
- setCFCMethod
- getOriginatorID
- getLogger
- getBuddyList
- getBuddyInfo
- IM gateway message sending commands
- IM Gateway GatewayHelper class methods
- onIncomingMessage
- onIMServerMessage
- onBuddyStatus
- onAddBuddyResponse
- onAddBuddyRequest
- IM Gateway CFC incoming message methods
- IM gateway methods and commands
- CFML CFEvent structure
- warn
- info
- setOriginatorID
- data command
- submit Multi command
- submit command
- setGatewayType
- setGatewayID
- setData
- setCFCListeners
- outgoingMessage
- getStatusTimeStamp
- numberOfMessagesReceived
- numberOfMessagesSent
- removeBuddy
- removeDeny
- removePermit
- setNickName
- setPermitMode
- setStatus
- SMS Gateway CFEvent structure and commands
- SMS Gateway incoming message CFEvent structure
- getStatusAsString
- getProtocolName
- getPermitMode
- getPermitList
- getNickName
- getName
- getDenyList
- getCustomAwayMessage
- getQueueSize
- getMaxQueueSize
- getHelper
- getGatewayType
- getGatewayServices
- getGatewayID_1
- getGatewayID
- getData
- getCFCTimeout
- setCFCTimeout
- getCFCPath
- getCFCMethod
- GatewayServices class
- Gateway interface
- GatewayHelper interface
- addPermit
- addDeny
- addBuddy
- error
- debug
- Logger class
- stop
- start
- CFML event gateway SendGatewayMessage data parameter
- restart
- fatal
- SMS gateway message sending commands
- ColdFusion C++ CFX Reference
- ColdFusion Java CFX reference
- WDDX JavaScript Objects
- Cloud services
- ColdFusion and GCP Storage
- ColdFusion and GCP Firestore
- ColdFusion and GCP PubSub
- ColdFusion and Amazon S3
- ColdFusion and DynamoDB
- ColdFusion and Amazon SQS
- ColdFusion and Amazon SNS
- ColdFusion and MongoDB
- ColdFusion and Azure Blob
- ColdFusion and Azure Service Bus
- Multi-cloud storage services
- Multi-cloud RDS databases
- ColdFusion and Azure Cosmos DB
Description
Determines the integer number of units by which date1 is less than date2.
Returns
A number of units, of type datepart.
Category
Function syntax
DateDiff(datepart, date1, date2)
See also
DateAdd, DatePart, CreateTimeSpan
History
ColdFusion MX:
- Changed how negative date differences are calculated: this function calculates negative date differences correctly; its output may be different from that in earlier releases.
Parameters
Parameter |
Description |
|---|---|
datepart |
String that specifies the units in which to count; for example yyyy requests a date difference in whole years.
Note: The mask w as weekdays is only valid for the 2018 release of ColdFusion. For 2016 and earlier versions of ColdFusion, w returns the number of weeks. |
date1 |
Date/time object, in the range 100 AD-9999 AD. |
date2 |
Date/time object, in the range 100 AD-9999 AD. |
Usage
The DateDiff function determines the number of complete datepart units between the two dates; for example, if the datepart parameter is "m" and the dates differ by 55 days, the function returns 1 .Enclose string constant dates in quotation marks. If the text contains only numbers (such 1932 ), and is not surrounded by quotation marks, ColdFusion interprets it as a date/time object, resulting in an incorrect value.
In the DateDiff function, there is a difference in how the date difference is calculated for the member function. For example, in the code below,
<cfscript>
date1="2018-09-25"
date2="2018-10-25"
diffA=dateDiff("ww", date1, date2)
writeOutput(diffA) // 4
diffB=date1.diff("ww",date2)
writeOutput(diffB) // -4
</cfscript>
The first writeOutput produces a difference of 4 weeks, whereas the second writeOutput produces a difference of -4 weeks. Using DateDiff, the difference is calculated as date2-date1, whereas using the member function, the difference is calculated as date1-date2.
It is a known behavior in ColdFusion and the results are as expected.
Example
<cfscript>
Date1 = "{ts '2018-11-15 12:13:50'}";
Date2 = "{ts '2018-12-15 12:13:50'}";
diff= DateDiff("d",Date1,Date2)
diff1= DateDiff("ww",Date1,Date2)
diff2= DateDiff("m",Date1,Date2)
writeOutput("difference in date is : " & diff & " days or" & "<br/>" )
writeOutput("difference in date is : " & diff1 & " weeks or" & "<br/>")
writeOutput("difference in date is : " & diff2 & " month" & "<br/>")
</cfscript>
Output
difference in date is : 30 days or
difference in date is : 4 weeks or
difference in date is : 1 month
Real-world use cases of the DateDiff function
Subscription management system
A SaaS platform tracking subscription periods, renewals, and billing cycles. Subscription businesses need to track billing cycles, send renewal reminders, and analyze customer lifecycle patterns based on precise date calculations.
<cfscript>
// Current date for calculations
today = now();
// Customer subscription data
subscriptions = [
{
customerName: "John Smith",
startDate: createDate(2024, 1, 15),
endDate: createDate(2024, 12, 15),
planType: "Annual Premium",
status: "active"
},
{
customerName: "Sarah Johnson",
startDate: createDate(2024, 6, 1),
endDate: createDate(2024, 7, 1),
planType: "Monthly Basic",
status: "expired"
},
{
customerName: "TechCorp Inc",
startDate: createDate(2023, 3, 10),
endDate: createDate(2025, 3, 10),
planType: "2-Year Enterprise",
status: "active"
},
{
customerName: "StartupXYZ",
startDate: createDate(2024, 10, 20),
endDate: createDate(2024, 11, 20),
planType: "Monthly Pro",
status: "active"
}
];
writeOutput("<h2>Subscription Management Dashboard</h2>");
writeOutput("<table border='1' cellpadding='8'>");
writeOutput("<tr><th>Customer</th><th>Plan</th><th>Days Active</th><th>Days Remaining</th><th>Status</th><th>Action Required</th></tr>");
for (sub in subscriptions) {
// Calculate how many days the subscription has been active
daysActive = DateDiff("d", sub.startDate, today);
// Calculate days remaining (negative if expired)
daysRemaining = DateDiff("d", today, sub.endDate);
// Calculate total subscription length in months
totalMonths = DateDiff("m", sub.startDate, sub.endDate);
// Determine status and actions
statusColor = "black";
actionRequired = "None";
if (daysRemaining < 0) {
statusColor = "red";
actionRequired = "Renewal Needed";
} else if (daysRemaining <= 7) {
statusColor = "orange";
actionRequired = "Send Renewal Reminder";
} else if (daysRemaining <= 30) {
statusColor = "blue";
actionRequired = "Pre-renewal Notice";
} else {
statusColor = "green";
actionRequired = "Monitor";
}
writeOutput("<tr>");
writeOutput("<td>" & sub.customerName & "</td>");
writeOutput("<td>" & sub.planType & " (" & totalMonths & " months)</td>");
writeOutput("<td>" & daysActive & " days</td>");
writeOutput("<td style='color: " & statusColor & ";'>" & daysRemaining & " days</td>");
writeOutput("<td style='color: " & statusColor & ";'>" & UCase(sub.status) & "</td>");
writeOutput("<td><strong>" & actionRequired & "</strong></td>");
writeOutput("</tr>");
}
writeOutput("</table>");
// Summary statistics
activeSubscriptions = 0;
expiringSOon = 0;
for (sub in subscriptions) {
daysRemaining = DateDiff("d", today, sub.endDate);
if (daysRemaining > 0) activeSubscriptions++;
if (daysRemaining > 0 && daysRemaining <= 30) expiringSoon++;
}
writeOutput("<h3>Summary</h3>");
writeOutput("<ul>");
writeOutput("<li><strong>Active Subscriptions:</strong> " & activeSubscriptions & "</li>");
writeOutput("<li><strong>Expiring in 30 days:</strong> " & expiringSoon & "</li>");
writeOutput("</ul>");
</cfscript>
Employee time tracking and payroll system
HR system calculating work hours, overtime, and employment duration. Accurate time calculations are essential for payroll processing, overtime calculation, and employment record keeping in HR systems.
<cfscript>
// Employee time tracking data
employees = [
{
name: "Alice Cooper",
hireDate: createDate(2022, 3, 15),
shiftStart: createDateTime(2024, 3, 15, 9, 0, 0),
shiftEnd: createDateTime(2024, 3, 15, 17, 30, 0),
lunchBreak: 30, // minutes
employeeType: "Full-time"
},
{
name: "Bob Wilson",
hireDate: createDate(2023, 8, 1),
shiftStart: createDateTime(2024, 3, 15, 14, 0, 0),
shiftEnd: createDateTime(2024, 3, 15, 22, 15, 0),
lunchBreak: 45,
employeeType: "Part-time"
},
{
name: "Carol Davis",
hireDate: createDate(2021, 11, 20),
shiftStart: createDateTime(2024, 3, 15, 6, 0, 0),
shiftEnd: createDateTime(2024, 3, 15, 18, 45, 0),
lunchBreak: 60,
employeeType: "Full-time"
}
];
// Payroll calculation function
function calculatePayroll(employee) {
result = {};
// Calculate employment duration
result.yearsEmployed = DateDiff("yyyy", employee.hireDate, now());
result.monthsEmployed = DateDiff("m", employee.hireDate, now());
result.daysEmployed = DateDiff("d", employee.hireDate, now());
// Calculate daily work hours
totalMinutesWorked = DateDiff("n", employee.shiftStart, employee.shiftEnd);
netMinutesWorked = totalMinutesWorked - employee.lunchBreak;
result.hoursWorked = netMinutesWorked / 60;
// Determine overtime (over 8 hours)
if (result.hoursWorked > 8) {
result.regularHours = 8;
result.overtimeHours = result.hoursWorked - 8;
} else {
result.regularHours = result.hoursWorked;
result.overtimeHours = 0;
}
// Calculate pay (example rates)
regularRate = 25.00; // $25/hour
overtimeRate = 37.50; // $37.50/hour (1.5x)
result.regularPay = result.regularHours * regularRate;
result.overtimePay = result.overtimeHours * overtimeRate;
result.totalPay = result.regularPay + result.overtimePay;
return result;
}
writeOutput("<h2>Employee Payroll Report - " & dateFormat(now(), "mm/dd/yyyy") & "</h2>");
writeOutput("<table border='1' cellpadding='8'>");
writeOutput("<tr><th>Employee</th><th>Employment Duration</th><th>Shift Times</th><th>Hours Worked</th><th>Regular Pay</th><th>Overtime Pay</th><th>Total Pay</th></tr>");
totalPayroll = 0;
for (employee in employees) {
payroll = calculatePayroll(employee);
totalPayroll += payroll.totalPay;
writeOutput("<tr>");
writeOutput("<td><strong>" & employee.name & "</strong><br><em>" & employee.employeeType & "</em></td>");
writeOutput("<td>" & payroll.yearsEmployed & " years<br>" &
payroll.monthsEmployed & " months<br>" &
payroll.daysEmployed & " days</td>");
writeOutput("<td>" & timeFormat(employee.shiftStart, "h:mm tt") & " - " &
timeFormat(employee.shiftEnd, "h:mm tt") & "<br>" &
"Lunch: " & employee.lunchBreak & " min</td>");
writeOutput("<td>" & numberFormat(payroll.hoursWorked, "9.9") & " hrs<br>" &
"(Regular: " & numberFormat(payroll.regularHours, "9.9") &
", OT: " & numberFormat(payroll.overtimeHours, "9.9") & ")</td>");
writeOutput("<td>$" & numberFormat(payroll.regularPay, "999.99") & "</td>");
if (payroll.overtimeHours > 0) {
writeOutput("<td style='color: green;'>$" & numberFormat(payroll.overtimePay, "999.99") & "</td>");
} else {
writeOutput("<td>$0.00</td>");
}
writeOutput("<td><strong>$" & numberFormat(payroll.totalPay, "999.99") & "</strong></td>");
writeOutput("</tr>");
}
//writeOutput("<tr style='background-color: #f0f0f0; font-weight: bold;'>");
writeOutput("<td colspan='6'>TOTAL DAILY PAYROLL</td>");
writeOutput("<td><strong>$" & numberFormat(totalPayroll, "999.99") & "</strong></td>");
writeOutput("</tr>");
writeOutput("</table>");
</cfscript>
Project management and deadline tracking
A software development team tracking project milestones and sprint progress. Project managers need precise timeline calculations to track progress, identify risks, and make data-driven decisions about resource allocation and deadline management.
<cfscript>
// Project and task data
projects = [
{
name: "E-commerce Website Redesign",
startDate: createDate(2024, 2, 1),
deadline: createDate(2024, 4, 15),
currentPhase: "Development",
completion: 65
},
{
name: "Mobile App Development",
startDate: createDate(2024, 1, 15),
deadline: createDate(2024, 3, 30),
currentPhase: "Testing",
completion: 85
},
{
name: "Database Migration",
startDate: createDate(2024, 3, 1),
deadline: createDate(2024, 3, 20),
currentPhase: "Planning",
completion: 25
},
{
name: "Security Audit",
startDate: createDate(2024, 2, 20),
deadline: createDate(2024, 3, 25),
currentPhase: "In Progress",
completion: 40
}
];
// Sprint tracking
currentSprint = {
sprintNumber: 5,
startDate: createDateTime(2024, 3, 11, 9, 0, 0),
endDate: createDateTime(2024, 3, 25, 17, 0, 0),
totalStoryPoints: 40,
completedStoryPoints: 28
};
function analyzeProject(project) {
result = {};
today = now();
// Calculate project timeline
result.totalDuration = DateDiff("d", project.startDate, project.deadline);
result.daysElapsed = DateDiff("d", project.startDate, today);
result.daysRemaining = DateDiff("d", today, project.deadline);
result.weeksRemaining = DateDiff("ww", today, project.deadline);
// Calculate progress metrics
result.timeElapsedPercent = (result.daysElapsed / result.totalDuration) * 100;
result.scheduleVariance = project.completion - result.timeElapsedPercent;
// Determine project status
if (result.daysRemaining < 0) {
result.status = "OVERDUE";
result.statusColor = "red";
} else if (result.scheduleVariance < -20) {
result.status = "BEHIND SCHEDULE";
result.statusColor = "red";
} else if (result.scheduleVariance < -10) {
result.status = "AT RISK";
result.statusColor = "orange";
} else if (result.scheduleVariance > 10) {
result.status = "AHEAD OF SCHEDULE";
result.statusColor = "green";
} else {
result.status = "ON TRACK";
result.statusColor = "blue";
}
return result;
}
writeOutput("<h2>Project Management Dashboard</h2>");
// Current sprint information
sprintDaysTotal = DateDiff("d", currentSprint.startDate, currentSprint.endDate);
sprintDaysElapsed = DateDiff("d", currentSprint.startDate, now());
sprintDaysRemaining = DateDiff("d", now(), currentSprint.endDate);
sprintHoursRemaining = DateDiff("h", now(), currentSprint.endDate);
//writeOutput("<div style='background-color: #e6f3ff; padding: 15px; margin: 10px; border: 1px solid #0066cc;'>");
//writeOutput("<h3>Current Sprint #" & currentSprint.sprintNumber & "</h3>");
writeOutput("<p><strong>Duration:</strong> " & sprintDaysTotal & " days (" &
dateFormat(currentSprint.startDate, "mm/dd") & " - " &
dateFormat(currentSprint.endDate, "mm/dd") & ")</p>");
writeOutput("<p><strong>Time Remaining:</strong> " & sprintDaysRemaining & " days (" &
sprintHoursRemaining & " hours)</p>");
writeOutput("<p><strong>Story Points:</strong> " & currentSprint.completedStoryPoints &
"/" & currentSprint.totalStoryPoints & " completed</p>");
writeOutput("</div>");
// Project status table
writeOutput("<table border='1' cellpadding='8'>");
writeOutput("<tr><th>Project</th><th>Timeline</th><th>Progress</th><th>Schedule Analysis</th><th>Status</th></tr>");
for (project in projects) {
analysis = analyzeProject(project);
writeOutput("<tr>");
writeOutput("<td><strong>" & project.name & "</strong><br>" &
"<em>" & project.currentPhase & "</em></td>");
writeOutput("<td>Duration: " & analysis.totalDuration & " days<br>" &
"Elapsed: " & analysis.daysElapsed & " days<br>" &
"Remaining: " & analysis.daysRemaining & " days (" &
analysis.weeksRemaining & " weeks)</td>");
writeOutput("<td>" & project.completion & "% complete<br>" &
"Time elapsed: " & numberFormat(analysis.timeElapsedPercent, "99.9") & "%</td>");
varianceText = "";
if (analysis.scheduleVariance > 0) {
varianceText = "+" & numberFormat(analysis.scheduleVariance, "99.9") & "% ahead";
} else {
varianceText = numberFormat(analysis.scheduleVariance, "99.9") & "% behind";
}
writeOutput("<td>" & varianceText & "</td>");
writeOutput("<td style='color: " & analysis.statusColor & "; font-weight: bold;'>" &
analysis.status & "</td>");
writeOutput("</tr>");
}
writeOutput("</table>");
// Summary metrics
onTimeProjects = 0;
riskyProjects = 0;
for (project in projects) {
analysis = analyzeProject(project);
if (analysis.status == "ON TRACK" || analysis.status == "AHEAD OF SCHEDULE") {
onTimeProjects++;
} else if (analysis.status == "AT RISK" || analysis.status == "BEHIND SCHEDULE") {
riskyProjects++;
}
}
writeOutput("<h3>Portfolio Summary</h3>");
writeOutput("<ul>");
writeOutput("<li><strong>Projects on track:</strong> " & onTimeProjects & "/" & arrayLen(projects) & "</li>");
writeOutput("<li><strong>Projects needing attention:</strong> " & riskyProjects & "</li>");
writeOutput("</ul>");
</cfscript>
Customer support ticket system
Help desk system tracking response times and SLA compliance. Customer support teams need precise time tracking to meet SLA commitments, measure performance, and identify areas for improvement in their support processes.
<cfscript>
// Support tickets with different priorities and SLA requirements
supportTickets = [
{
ticketId: "TKT-001",
customerTier: "Enterprise",
priority: "Critical",
submittedDate: createDateTime(2024, 3, 14, 14, 30, 0),
firstResponseDate: createDateTime(2024, 3, 14, 14, 45, 0),
resolvedDate: createDateTime(2024, 3, 14, 16, 20, 0),
status: "Resolved"
},
{
ticketId: "TKT-002",
customerTier: "Professional",
priority: "High",
submittedDate: createDateTime(2024, 3, 14, 9, 15, 0),
firstResponseDate: createDateTime(2024, 3, 14, 11, 30, 0),
resolvedDate: createDateTime(2024, 3, 15, 10, 45, 0),
status: "Resolved"
},
{
ticketId: "TKT-003",
customerTier: "Basic",
priority: "Medium",
submittedDate: createDateTime(2024, 3, 13, 16, 45, 0),
firstResponseDate: createDateTime(2024, 3, 14, 9, 0, 0),
resolvedDate: "", // Still open
status: "In Progress"
},
{
ticketId: "TKT-004",
customerTier: "Enterprise",
priority: "Low",
submittedDate: createDateTime(2024, 3, 12, 13, 20, 0),
firstResponseDate: createDateTime(2024, 3, 12, 15, 10, 0),
resolvedDate: createDateTime(2024, 3, 13, 11, 30, 0),
status: "Resolved"
}
];
// SLA requirements (in hours)
slaRequirements = {
"Enterprise": {
"Critical": {responseTime: 0.25, resolutionTime: 4}, // 15 min, 4 hours
"High": {responseTime: 1, resolutionTime: 8},
"Medium": {responseTime: 2, resolutionTime: 24},
"Low": {responseTime: 4, resolutionTime: 72}
},
"Professional": {
"Critical": {responseTime: 1, resolutionTime: 8},
"High": {responseTime: 2, resolutionTime: 16},
"Medium": {responseTime: 4, resolutionTime: 48},
"Low": {responseTime: 8, resolutionTime: 120}
},
"Basic": {
"Critical": {responseTime: 2, resolutionTime: 24},
"High": {responseTime: 4, resolutionTime: 48},
"Medium": {responseTime: 8, resolutionTime: 96},
"Low": {responseTime: 24, resolutionTime: 168}
}
};
function analyzeSLA(ticket) {
result = {};
sla = slaRequirements[ticket.customerTier][ticket.priority];
// Calculate response time
if (ticket.firstResponseDate != "") {
result.responseHours = DateDiff("n", ticket.submittedDate, ticket.firstResponseDate) / 60;
result.responseSLA = result.responseHours <= sla.responseTime ? "Met" : "Missed";
} else {
result.responseHours = DateDiff("n", ticket.submittedDate, now()) / 60;
result.responseSLA = "Pending";
}
// Calculate resolution time
if (ticket.resolvedDate != "") {
result.resolutionHours = DateDiff("n", ticket.submittedDate, ticket.resolvedDate) / 60;
result.resolutionSLA = result.resolutionHours <= sla.resolutionTime ? "Met" : "Missed";
} else {
result.resolutionHours = DateDiff("n", ticket.submittedDate, now()) / 60;
if (result.resolutionHours > sla.resolutionTime) {
result.resolutionSLA = "At Risk";
} else {
result.resolutionSLA = "In Progress";
}
}
result.slaTarget = sla;
return result;
}
writeOutput("<h2>Support Ticket SLA Dashboard</h2>");
writeOutput("<table border='1' cellpadding='8'>");
writeOutput("<tr><th>Ticket ID</th><th>Customer Tier</th><th>Priority</th><th>Age</th><th>Response Time</th><th>Resolution Time</th><th>SLA Status</th></tr>");
slaStats = {met: 0, missed: 0, pending: 0};
for (ticket in supportTickets) {
analysis = analyzeSLA(ticket);
// Calculate ticket age
if (ticket.status == "Resolved") {
ticketAge = DateDiff("h", ticket.submittedDate, ticket.resolvedDate);
ageText = ticketAge & " hours (closed)";
} else {
ticketAge = DateDiff("h", ticket.submittedDate, now());
ageText = ticketAge & " hours (open)";
}
// SLA status color coding
responseColor = "black";
resolutionColor = "black";
if (analysis.responseSLA == "Met") responseColor = "green";
else if (analysis.responseSLA == "Missed") responseColor = "red";
else responseColor = "orange";
if (analysis.resolutionSLA == "Met") resolutionColor = "green";
else if (analysis.resolutionSLA == "Missed") resolutionColor = "red";
else if (analysis.resolutionSLA == "At Risk") resolutionColor = "orange";
writeOutput("<tr>");
writeOutput("<td><strong>" & ticket.ticketId & "</strong></td>");
writeOutput("<td>" & ticket.customerTier & "</td>");
writeOutput("<td>" & ticket.priority & "</td>");
writeOutput("<td>" & ageText & "</td>");
writeOutput("<td style='color: " & responseColor & ";'>" &
numberFormat(analysis.responseHours, "99.9") & "h<br>" &
"(SLA: " & analysis.slaTarget.responseTime & "h)<br>" &
"<strong>" & analysis.responseSLA & "</strong></td>");
writeOutput("<td style='color: " & resolutionColor & ";'>" &
numberFormat(analysis.resolutionHours, "99.9") & "h<br>" &
"(SLA: " & analysis.slaTarget.resolutionTime & "h)<br>" &
"<strong>" & analysis.resolutionSLA & "</strong></td>");
// Overall SLA status
overallStatus = "Good";
overallColor = "green";
if (analysis.responseSLA == "Missed" || analysis.resolutionSLA == "Missed") {
overallStatus = "SLA Breach";
overallColor = "red";
slaStats.missed++;
} else if (analysis.responseSLA == "Pending" || analysis.resolutionSLA == "At Risk") {
overallStatus = "At Risk";
overallColor = "orange";
slaStats.pending++;
} else {
slaStats.met++;
}
writeOutput("<td style='color: " & overallColor & "; font-weight: bold;'>" & overallStatus & "</td>");
writeOutput("</tr>");
}
writeOutput("</table>");
// SLA compliance summary
totalTickets = arrayLen(supportTickets);
complianceRate = (slaStats.met / totalTickets) * 100;
writeOutput("<h3>SLA Compliance Summary</h3>");
//writeOutput("<div style='background-color: #f0f8ff; padding: 15px; border: 1px solid #ccc;'>");
writeOutput("<p><strong>Total Tickets:</strong> " & totalTickets & "</p>");
writeOutput("<p><strong>SLA Met:</strong> " & slaStats.met & " (" & numberFormat(complianceRate, "99.9") & "%)</p>");
writeOutput("<p><strong>SLA Breached:</strong> " & slaStats.missed & "</p>");
writeOutput("<p><strong>At Risk:</strong> " & slaStats.pending & "</p>");
writeOutput("</div>");
</cfscript>

