Working with Dates¶
This guide demonstrates date and time calculations in EverSharp, including age calculation, date ranges, date formatting, and common date operations.
Date Types¶
EverSharp has two date types:
- DateTime: Date and time (e.g.,
2024-03-15 14:30:00) - DateOnly: Date without time (e.g.,
2024-03-15)
Getting Current Date and Time¶
Current Date and Time¶
// Get current date and time
now = $Now(); // Returns: DateTime (e.g., 2024-11-28 14:30:45)
// Get current date (no time)
today = $Today(); // Returns: DateOnly (e.g., 2024-11-28)
Creating Specific Dates¶
// Parse date from string (ISO 8601 format)
birthDate = $ToDate("1990-05-15"); // Returns: DateTime (1990-05-15 00:00:00)
// Parse date with time
appointmentTime = $ToDate("2024-12-01 10:30:00");
// Parse date in local timezone
localDate = $ToDate("2024-03-15");
// Parse date in UTC timezone
utcDate = $ToDateUTC("2024-03-15");
Date Arithmetic¶
Adding Time¶
startDate = $ToDate("2024-01-15");
// Add days
futureDate = $AddDays(startDate, 30); // 2024-02-14
// Add months
nextMonth = $AddMonths(startDate, 1); // 2024-02-15
// Add years
nextYear = $AddYears(startDate, 1); // 2025-01-15
// Add hours, minutes, seconds
meetingTime = $ToDate("2024-12-01 10:00:00");
endTime = $AddHours(meetingTime, 2); // 2024-12-01 12:00:00
reminderTime = $AddMinutes(meetingTime, -15); // 2024-12-01 09:45:00
Calculating Date Differences¶
startDate = $ToDate("2024-01-01");
endDate = $ToDate("2024-12-31");
// Calculate differences
days = $DifferenceInDays(startDate, endDate); // 365
hours = $DifferenceInHours(startDate, endDate); // 8760
minutes = $DifferenceInMinutes(startDate, endDate); // 525600
Extracting Date Components¶
Year, Month, Day¶
date = $ToDate("2024-11-28");
year = $Year(date); // 2024
month = $Month(date); // 11
day = $Day(date); // 28
Date Boundaries¶
someDateTime = $ToDate("2024-11-28 14:30:00");
// Start of day (00:00:00)
dayStart = $StartOfDay(someDateTime); // 2024-11-28 00:00:00
// End of day (23:59:59)
dayEnd = $EndOfDay(someDateTime); // 2024-11-28 23:59:59
Practical Examples¶
Example 1: Calculate Age¶
Calculate a person's age in years:
calculateAge = function (birthDate) {
today = $Today();
years = $DifferenceInYears(birthDate, today);
return years;
};
birthDate = $ToDate("1990-05-15");
age = calculateAge(birthDate); // Returns current age (e.g., 34)
Example 2: Age-Based Premium¶
Calculate insurance premium based on age:
calculateAgePremium = function (birthDate, basePremium) {
age = $DifferenceInYears(birthDate, $Today());
if (age < 25) {
multiplier = 1.5; // Higher rate for younger drivers
} else if (age < 65) {
multiplier = 1.0; // Standard rate
} else {
multiplier = 1.3; // Higher rate for seniors
}
return basePremium * multiplier;
};
birthDate = $ToDate("1980-06-15");
premium = calculateAgePremium(birthDate, 1000); // Returns: 1000 (age 44)
Example 3: Check Date Range¶
Check if a date falls within a range:
isDateInRange = function (checkDate, startDate, endDate) {
// Date is in range if it's >= start AND <= end
afterStart = $DifferenceInDays(startDate, checkDate) >= 0;
beforeEnd = $DifferenceInDays(checkDate, endDate) >= 0;
return afterStart && beforeEnd;
};
policyStart = $ToDate("2024-01-01");
policyEnd = $ToDate("2024-12-31");
claimDate = $ToDate("2024-06-15");
isValid = isDateInRange(claimDate, policyStart, policyEnd); // true
Example 4: Days Until Event¶
Calculate days remaining until a future date:
daysUntil = function (targetDate) {
today = $Today();
days = $DifferenceInDays(today, targetDate);
return days;
};
renewalDate = $ToDate("2025-03-15");
daysRemaining = daysUntil(renewalDate); // Days until March 15, 2025
// Use in conditional logic
if (daysRemaining <= 30) {
status = "Renewal Due Soon";
} else if (daysRemaining <= 60) {
status = "Renewal Approaching";
} else {
status = "Active";
}
Example 5: Policy Term Dates¶
Calculate policy start and end dates:
calculatePolicyDates = function (effectiveDate, termMonths) {
startDate = $StartOfDay(effectiveDate);
endDate = $AddMonths(startDate, termMonths);
endDate = $AddDays(endDate, -1); // Last day of coverage
endDate = $EndOfDay(endDate); // End at 23:59:59
return {
startDate: startDate,
endDate: endDate,
termMonths: termMonths,
};
};
effectiveDate = $ToDate("2024-01-15");
policy = calculatePolicyDates(effectiveDate, 12);
// policy.startDate: 2024-01-15 00:00:00
// policy.endDate: 2025-01-14 23:59:59
// policy.termMonths: 12
Example 6: Calculate Tenure¶
Calculate years and months of service:
calculateTenure = function (hireDate) {
today = $Today();
totalYears = $DifferenceInYears(hireDate, today);
// Calculate remaining months
yearAnniversary = $AddYears(hireDate, totalYears);
remainingMonths = $Month(today) - $Month(yearAnniversary);
if (remainingMonths < 0) {
remainingMonths = remainingMonths + 12;
totalYears = totalYears - 1;
}
return {
years: totalYears,
months: remainingMonths,
};
};
hireDate = $ToDate("2020-03-15");
tenure = calculateTenure(hireDate);
// tenure.years: 4
// tenure.months: 8
// (as of November 2024)
Example 7: Business Days Calculation¶
Count business days (excluding weekends):
// Note: This is a simplified version that only excludes weekends
// For a production system, you'd also need to exclude holidays
countBusinessDays = function (startDate, endDate) {
totalDays = $DifferenceInDays(startDate, endDate);
// Rough calculation: 5 business days per 7 calendar days
weeks = totalDays / 7;
businessDays = weeks * 5;
// Handle remaining days
remainder = totalDays % 7;
businessDays = businessDays + remainder;
// Account for potential weekend days in remainder
// (Simplified - exact calculation would need day of week)
if (remainder > 5) {
businessDays = businessDays - 2;
} else if (remainder > 0) {
businessDays = businessDays - 0;
}
return $Round(businessDays);
};
start = $ToDate("2024-01-01");
end = $ToDate("2024-01-31");
workDays = countBusinessDays(start, end); // Approximately 22-23 business days
Example 8: Age Verification¶
Verify age requirements for eligibility:
meetsAgeRequirement = function (birthDate, minimumAge) {
today = $Today();
age = $DifferenceInYears(birthDate, today);
return age >= minimumAge;
};
// Check if person is at least 18
birthDate = $ToDate("2008-03-15");
canEnroll = meetsAgeRequirement(birthDate, 18);
if (canEnroll) {
message = "Eligible for enrollment";
} else {
age = $DifferenceInYears(birthDate, $Today());
yearsUntilEligible = 18 - age;
message =
"Not eligible. Eligible in " + $ToString(yearsUntilEligible) + " years";
}
Example 9: Grace Period Check¶
Check if payment is within grace period:
isWithinGracePeriod = function (dueDate, graceDays) {
today = $Today();
daysPastDue = $DifferenceInDays(dueDate, today);
if (daysPastDue <= 0) {
return true; // Not yet due or on due date
} else if (daysPastDue <= graceDays) {
return true; // Within grace period
} else {
return false; // Grace period expired
}
};
dueDate = $ToDate("2024-11-15");
inGracePeriod = isWithinGracePeriod(dueDate, 30);
if (inGracePeriod) {
status = "Active";
} else {
status = "Lapsed";
}
Example 10: Policy Renewal Date¶
Calculate renewal date (one day after expiration):
calculateRenewalDate = function (expirationDate) {
// Renewal starts the day after expiration
renewalDate = $AddDays(expirationDate, 1);
renewalDate = $StartOfDay(renewalDate);
return renewalDate;
};
expirationDate = $ToDate("2024-12-31 23:59:59");
renewalDate = calculateRenewalDate(expirationDate);
// Returns: 2025-01-01 00:00:00
Date Formatting¶
Using ToString with Format¶
date = $ToDate("2024-11-28 14:30:00");
// Common formats
formatted1 = date.ToString("yyyy-MM-dd"); // "2024-11-28"
formatted2 = date.ToString("MM/dd/yyyy"); // "11/28/2024"
formatted3 = date.ToString("dd-MMM-yyyy"); // "28-Nov-2024"
formatted4 = date.ToString("yyyy-MM-dd HH:mm:ss"); // "2024-11-28 14:30:00"
formatted5 = date.ToString("MMMM dd, yyyy"); // "November 28, 2024"
// Time formats
timeOnly = date.ToString("HH:mm:ss"); // "14:30:00"
time12Hour = date.ToString("hh:mm tt"); // "02:30 PM"
Date Display Function¶
formatDateForDisplay = function (date, format) {
if (format == "short") {
return date.ToString("MM/dd/yyyy");
} else if (format == "long") {
return date.ToString("MMMM dd, yyyy");
} else if (format == "iso") {
return date.ToString("yyyy-MM-dd");
} else {
return date.ToString("MM/dd/yyyy");
}
};
date = $ToDate("2024-11-28");
display1 = formatDateForDisplay(date, "short"); // "11/28/2024"
display2 = formatDateForDisplay(date, "long"); // "November 28, 2024"
display3 = formatDateForDisplay(date, "iso"); // "2024-11-28"
Common Patterns¶
Date Validation¶
isValidDateRange = function (startDate, endDate) {
// End date must be after start date
diff = $DifferenceInDays(startDate, endDate);
return diff > 0;
};
start = $ToDate("2024-01-01");
end = $ToDate("2024-12-31");
isValid = isValidDateRange(start, end); // true
Compare Dates¶
isDateAfter = function (date1, date2) {
diff = $DifferenceInDays(date2, date1);
return diff > 0;
};
isSameDate = function (date1, date2) {
diff = $DifferenceInDays(date1, date2);
return diff == 0;
};
date1 = $ToDate("2024-12-01");
date2 = $ToDate("2024-11-01");
isAfter = isDateAfter(date1, date2); // true (Dec 1 is after Nov 1)
isSame = isSameDate(date1, date2); // false
Date Range Overlap¶
doRangesOverlap = function (start1, end1, start2, end2) {
// Ranges overlap if:
// - start1 is before end2 AND end1 is after start2
condition1 = $DifferenceInDays(start1, end2) >= 0;
condition2 = $DifferenceInDays(start2, end1) >= 0;
return condition1 && condition2;
};
// Policy 1: Jan-Jun 2024
policy1Start = $ToDate("2024-01-01");
policy1End = $ToDate("2024-06-30");
// Policy 2: May-Dec 2024
policy2Start = $ToDate("2024-05-01");
policy2End = $ToDate("2024-12-31");
hasOverlap = doRangesOverlap(
policy1Start,
policy1End,
policy2Start,
policy2End
);
// true (May and June overlap)
Best Practices¶
Always Use Timezone-Aware Functions¶
// Prefer explicit timezone handling
localDate = $ToDate("2024-03-15"); // Local timezone
utcDate = $ToDateUTC("2024-03-15"); // UTC timezone
// Convert UTC to local if needed
localFromUtc = $ConvertTimeFromUtc(utcDate, "Eastern Standard Time");
Use Date Boundaries for Comparisons¶
// When comparing dates that might include times
// Use StartOfDay/EndOfDay for accurate comparisons
effectiveDate = $ToDate("2024-01-15 10:30:00");
checkDate = $ToDate("2024-01-15");
// Wrong: might fail due to time component
// isEffective = effectiveDate == checkDate;
// Correct: compare just the date part
effectiveDay = $StartOfDay(effectiveDate);
checkDay = $StartOfDay(checkDate);
isEffective = $DifferenceInDays(effectiveDay, checkDay) == 0; // true
Handle Edge Cases¶
// Account for leap years when adding years
addYearsSafe = function (date, years) {
// AddYears handles leap year edge cases automatically
newDate = $AddYears(date, years);
return newDate;
};
// Feb 29, 2024 + 1 year = Feb 28, 2025 (not a leap year)
leapDate = $ToDate("2024-02-29");
nextYear = addYearsSafe(leapDate, 1); // 2025-02-28
Next Steps¶
- Array Operations - Working with collections of dates
- Object Manipulation - Creating date-based objects
- Business Rules - Complex calculations with dates
See Also¶
- Date and Time Functions - Complete date function reference
- Conversion Functions - Date parsing and formatting
- Data Types - DateTime and DateOnly types