Sub topic 7
Working with dates and times
This chapter assumes you can create a formula field, choose its return type, and use the basic operators and functions from earlier chapters. It covers how Salesforce formulas treat dates and date/times, the arithmetic rules, the conversion functions, and the mistakes that cause wrong results.
Three related data types
Formulas work with three types of time values.
| Type | Holds | Example source | Function that returns it |
|---|---|---|---|
| Date | A calendar day, with no time | `CloseDate` | `TODAY()`, `DATE()` |
| Date/Time | A day plus a time, stored in UTC | `CreatedDate` | `NOW()`, `DATETIMEVALUE()` |
| Time | A time of day, with no date | A custom Time field | `TIMEVALUE()` |
TODAY() and NOW() are evaluated each time the formula is read. A formula that uses either one always reflects the current moment. It is never a snapshot from when the record was saved.
Date arithmetic
The arithmetic rules depend on the types involved.
- Date minus Date gives a Number of days.
- Date plus or minus a Number gives a Date, where the number counts days.
- Date/Time minus Date/Time gives a Number of days, including a fraction.
- Date/Time plus or minus a Number gives a Date/Time, where the number counts days.
The simplest example subtracts today from a close date:
CloseDate - TODAY()Set the return type to Number with 0 decimal places. The result is positive for future dates, 0 for today, and negative for past dates.
To compute a due date 30 days after a start date, use a Date return type:
Start_Date__c + 30Because Date/Time subtraction returns days, you convert to smaller units by multiplying. To show how many hours a record has existed, use a Number return type with 1 decimal place:
ROUND((NOW() - CreatedDate) * 24, 1)To add one hour to a Date/Time, add 1/24:
Scheduled_Start__c + 1/24Converting between Date and Date/Time
You can't subtract a Date from a Date/Time and expect a meaningful result. Convert one side first.
Use the diagram below as a map of the conversion functions.
A common use is the age of a record in whole days:
TODAY() - DATEVALUE(CreatedDate)Both operands are now Dates, so the result is a whole number.
Building and taking apart dates
DATE(year, month, day) builds a Date from three numbers. YEAR(), MONTH(), and DAY() extract parts of a Date. WEEKDAY() returns 1 for Sunday through 7 for Saturday.
To flag weekend close dates:
IF(OR(WEEKDAY(CloseDate) = 1, WEEKDAY(CloseDate) = 7), "Weekend", "Weekday")To get the first day of the close date's month:
DATE(YEAR(CloseDate), MONTH(CloseDate), 1)To add months, use ADDMONTHS() instead of adding 30 or 31. It also handles month ends. If the result month is shorter than the starting day, it returns the last valid day of that month.
ADDMONTHS(Contract_Start__c, 12)Writing DATE(YEAR(d), MONTH(d) + 12, DAY(d)) by hand fails for dates such as January 31 plus one month, because DATE() raises an error for a day that doesn't exist.
Time zones
A Date/Time is stored in UTC and displayed in each user's time zone. A Date has no time zone. This causes a subtle problem when you convert between the two.
DATEVALUE(CreatedDate)can return a different calendar day than the one a user sees near midnight, depending on the time zone used for the conversion.TODAY()is a Date, so it follows the running user's day, not UTC.
If your logic depends on the exact day of a Date/Time value, test it with a record created close to midnight in a time zone other than yours.
Handling blank dates
A blank Date makes date arithmetic unreliable. Depending on the field's "treat blank fields as zeroes" setting, a blank date either produces a blank result or is treated as a very old date, which gives a huge number of days. Guard against blanks explicitly:
IF(ISBLANK(Renewal_Date__c), NULL, Renewal_Date__c - TODAY())For a Number return type, NULL yields an empty field instead of a misleading value. Checking ISBLANK() first is the same safe-formula habit you used for division by zero.
Using dates with conditions and text
Use TEXT() to include a date in a text result. For a Date, the output format is YYYY-MM-DD, regardless of the user's locale:
"Due on " & TEXT(Due_Date__c)You can compare dates directly. This Text formula labels an overdue item:
IF(AND(NOT(ISBLANK(Due_Date__c)), Due_Date__c < TODAY()), "Overdue", "On time")Combine date arithmetic with CASE or nested IF when you need buckets, for example a label of "This week" for 0 to 7 days away.
Common errors
- Wrong return type.
CloseDate - TODAY()returns a Number. If you pick Date as the return type, the field won't save. - Adding a Date to a Date. This isn't allowed. Subtract them to get a number of days, or add a number to one Date.
- Mixing Date and Date/Time.
NOW() - CloseDateproduces an error or an unintended result. Convert withDATEVALUE()orDATETIMEVALUE(). - Expecting a snapshot. A formula containing
TODAY()changes every day. If you need the value as of a moment in the past, store it in a regular field with Flow or Apex. - Filtering on these fields in SOQL. Formulas that use
TODAY()orNOW()can't be indexed, so filtering large tables on them is slow. Filter on the underlying date field instead.
Practice
Exercise
A custom Date field Warranty_End__c holds the day a warranty expires. Write a Number formula that shows the days remaining, shows nothing when the field is blank, and is negative after expiry.
Show answer
IF(ISBLANK(WarrantyEndc), NULL, WarrantyEnd__c - TODAY())
Exercise
You need the number of whole days since a record was created. CreatedDate is a Date/Time and TODAY() is a Date. Write the formula and explain why it needs a conversion.
Show answer
TODAY() - DATEVALUE(CreatedDate). Subtracting a Date/Time from a Date mixes types. DATEVALUE converts CreatedDate to a Date, so both sides are Dates and the result is a whole number of days.
Exercise
Why should you use ADDMONTHS(ContractStartc, 1) instead of ContractStart__c + 30 to find a monthly renewal date?
Show answer
Months have different lengths, so adding 30 days drifts away from the same day of the month. ADDMONTHS keeps the day of the month and, when the next month is shorter, returns that month's last day.