Whatever message this page gives is out now! Go check it out!

DateDiff

Last update:
May 18, 2026

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

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.
  • yyyy : Years
  • q: Quarters
  • m: Months
  • y: Days of year (same as d)
  • d: Days
  • w: Weekdays
  • ww : Weeks
  • h: Hours
  • n: Minutes
  • s: Seconds
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.
Note:
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>

Share this page

Was this page helpful?
We're glad. Tell us how this page helped.
We're sorry. Can you tell us what didn't work for you?
Thank you for your feedback. Your response will help improve this page.

On this page