Sub topic 7
Working with dates and times
This chapter assumes you can create a formula field and choose its return type. It also assumes you know the basic operators from earlier chapters.
Date and Date/Time are different types
A Date field holds a day, such as CloseDate. A Date/Time field holds a day and a time, such as CreatedDate. Formulas treat them differently, and mixing them is the most common date error.
| Expression | Result type | Unit |
|---|---|---|
| Date - Date | Number | Days |
| Date/Time - Date/Time | Number | Days, with a fraction |
| Date + Number | Date | Adds days |
| Date/Time + Number | Date/Time | Adds days (0.5 is 12 hours) |
| Date - Date/Time | Error | Convert one side first |
TODAY and NOW
TODAY() returns the current date. NOW() returns the current date and time. Salesforce stores Date/Time values in GMT and displays them in the user's time zone.
A formula field is not stored. It is evaluated each time a record is read, so these functions always reflect the moment of reading.
This formula returns a Number with 0 decimal places. It gives the days until the close date and is negative when the date is in the past.
CloseDate - TODAY()To measure an age in days with a fraction, subtract two Date/Time values. Set the Number field to 2 decimal places.
NOW() - CreatedDateConverting between types
Use DATEVALUE() to turn a Date/Time into a Date. Use DATETIMEVALUE() to go the other way. Converting a Date/Time with DATEVALUE() uses the user's time zone, so the date can differ between users near midnight.
This formula counts the days between creation and the expected close:
CloseDate - DATEVALUE(CreatedDate)Shifting dates
ADDMONTHS(date, n) moves a date by whole months. If the target month is shorter, Salesforce uses the last day of that month. Set the return type to Date.
ADDMONTHS(CloseDate, 3)For a flag that depends on today's date, combine the date with IF. This formula uses a Text return type:
IF(AND(NOT(IsClosed), CloseDate < TODAY()), "Overdue", "On track")Common errors
- Wrong return type. Subtracting two dates returns a Number. If the field is set to Date, you get a syntax error.
- Mixed types.
CloseDate - CreatedDatefails. Wrap the Date/Time inDATEVALUE(). - Blank dates. A blank date makes the whole result blank or wrong. Guard with
IF(ISBLANK(CloseDate), null, CloseDate - TODAY()). - Expecting hours. Date arithmetic returns days. Multiply by 24 for hours.
Exercise
A Number formula on Opportunity must return the whole hours since the record was created. Which formula works, and why does NOW() - CreatedDate alone not give hours?
Show answer
Use (NOW() - CreatedDate) * 24 with the Number field set to 0 decimal places. Subtracting two Date/Time values returns days with a fractional part, so you multiply by 24 to convert days to hours.