Skip to content

calculateDaysDifference — GTM Variable Template for Date

VARIABLES › DATE
calculateDaysDifference CORE Date

Calculates the difference in days between two dates in YYYY-MM-DD format. Returns positive if end date is after start date.


When to Use This

Date Formatting

Format and transform date values into human-readable or machine-readable strings.

Formatting

Normalize casing, spacing, encoding, and presentation of data values.

Date & Time

Calculate durations, differences, and time-based operations on date values.


Examples

Positive day difference
INPUT
Start Date: 2024-01-01
End Date: 2024-01-10
OUTPUT
9
Same dates return 0
INPUT
Start Date: 2024-06-15
End Date: 2024-06-15
OUTPUT
0
Invalid format returns undefined
INPUT
Start Date: 2024/01/01
End Date: 2024-01-10
OUTPUT
undefined

GTM Configuration

This is what you'll see when you open this variable in Google Tag Manager. Hover the icons for details.

calculateDaysDifference
Start Date
▶️ Start date in YYYY-MM-DD format.

Supported formats:
  ✓ String
End Date
⏹️ End date in YYYY-MM-DD format.

Supported formats:
  ✓ String
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the input before internal logic (e.g., convert object to string, normalize case). Internal transformations such as case handling will still apply afterward.
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the result before returning it (e.g., str => str + ' €', val => val !== undefined for boolean conversion). Useful for chaining transformations on the output.
Start Date string
💡 Type any text to see the result update live
🎯 Using special value — click input to type instead
Test with:
Falsy
Truthy
End Date string
calculateDaysDifference()


Under the Hood

📜 View Implementation Code
/**
* Calculate the difference in days between two dates in YYYY-MM-DD format without using the Date object.
* 
* @param {string} data.src - Start date in YYYY-MM-DD format.
* @param {string} data.end - End date in YYYY-MM-DD format.
* @param {Function|string} [data.out] - Optional output handler: function to transform result or string with format.
*
* Direct-mode specific parameters:
* @param {Function} [data.pre] - Optional pre-processor function to transform src before calculation.
* 
* @returns {number|undefined} The difference in days (positive if endDate > startDate), or undefined if input is invalid.
*
* @framework ggLowCodeGTMKit
*/
const makeNumber = require('makeNumber');

const calculateDaysDifference = function(startDate, endDate) {
   if (typeof startDate !== 'string' || typeof endDate !== 'string') { return undefined; }
   const reDateFormatISO8601 = "^(\\d{4})-(\\d{2})-(\\d{2})$";
   const startDateMatchParts = startDate.match(reDateFormatISO8601);
   const endDateMatchParts = endDate.match(reDateFormatISO8601);
   if (startDateMatchParts === null || endDateMatchParts === null) { return undefined; }
   
   function calculateDaysSinceEpoch(year, month, day) {
       function isLeapYear(year) {
           return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
       }
       
       const daysInFebruary = isLeapYear(year) ? 29 : 28;
       
       // Days in each month including a dummy value for index 0
       const daysInMonth = [0, 31, daysInFebruary, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
       
       if (day > daysInMonth[month]) {
           return undefined;
       }
       
       // Days from 1970 to the year before
       let totalDays = 0;
       for (let y = 1970; y < year; y++) {
           totalDays += isLeapYear(y) ? 366 : 365;
       }
       
       // Add days from months in the current year
       for (let m = 1; m < month; m++) {
           totalDays += daysInMonth[m];
       }
       
       // Add days from the current month
       totalDays += day - 1;
       
       return totalDays;
   }
   
   const startTotalDays = calculateDaysSinceEpoch(makeNumber(startDateMatchParts[1]), makeNumber(startDateMatchParts[2]), makeNumber(startDateMatchParts[3]));
   const endTotalDays = calculateDaysSinceEpoch(makeNumber(endDateMatchParts[1]), makeNumber(endDateMatchParts[2]), makeNumber(endDateMatchParts[3]));
   return endTotalDays - startTotalDays;
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// calculateDaysDifference - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const value = applyCast(data.pre, data.src);
return out(calculateDaysDifference(value, data.end));
// ===============================================================================
// calc
🧪 View Test Scenarios (6 tests)
✅ '[example] Positive day difference'
✅ '[example] Same dates return 0'
✅ End date before start date - returns negative number
✅ Dates spanning leap year - handles leap year correctly
✅ '[example] Invalid format returns undefined'
✅ Invalid input - returns undefined