Sub topic 7
Date literals and date filters
This chapter assumes you can write a basic inline SOQL query with a WHERE clause and a bind variable, and that you know the difference between the Date and Datetime types in Apex. It builds on filtering with WHERE and covers how to filter on date and time fields without hard-coding dates.
Date and Datetime fields
SOQL has two field types for time values:
- Date fields store a calendar day with no time, such as
Opportunity.CloseDate. - Datetime fields store a moment in time, such as
CreatedDate,LastModifiedDate, andSystemModstamp.
Datetime values are stored in UTC and shown in the running user's time zone. This difference matters when you filter, as the sections below show.
Date and Datetime formats in a query
When you write a value directly in a query, it is not quoted. Quoting it turns it into a string and the query fails with a type error.
| Type | Format | Example |
|---|---|---|
| Date | `YYYY-MM-DD` | `2026-11-30` |
| Datetime in UTC | `YYYY-MM-DDThh:mm:ssZ` | `2026-11-30T09:30:00Z` |
| Datetime with offset | `YYYY-MM-DDThh:mm:ss+hh:mm` | `2026-11-30T09:30:00+01:00` |
List<Opportunity> opps = [
SELECT Id, Name, CloseDate
FROM Opportunity
WHERE CloseDate >= 2026-01-01 AND CloseDate <= 2026-03-31
];
List<Account> recent = [
SELECT Id, Name
FROM Account
WHERE CreatedDate >= 2026-11-01T00:00:00Z
];
System.debug(opps.size() + ' opportunities, ' + recent.size() + ' accounts');Hard-coded dates go stale. Date literals solve that.
Date literals
A date literal is a keyword that SOQL resolves to a date range when the query runs. It is not quoted and not a string. WHERE CloseDate = THIS_MONTH matches every opportunity that closes in the current month, whatever the month is today.
List<Opportunity> closingThisMonth = [
SELECT Id, Name, CloseDate, Amount
FROM Opportunity
WHERE CloseDate = THIS_MONTH
ORDER BY CloseDate
];
for (Opportunity o : closingThisMonth) {
System.debug(o.Name + ' closes on ' + o.CloseDate);
}The = operator here means "falls inside the range the literal describes". You can also use <, >, <=, and >=. In that case the literal is compared against the start or end of its range, depending on the operator.
Fixed literals
These need no number.
| Literal | Range |
|---|---|
| `YESTERDAY`, `TODAY`, `TOMORROW` | One day |
| `LAST_WEEK`, `THIS_WEEK`, `NEXT_WEEK` | One week |
| `LAST_MONTH`, `THIS_MONTH`, `NEXT_MONTH` | One calendar month |
| `LAST_90_DAYS`, `NEXT_90_DAYS` | 90 days back or forward |
| `THIS_QUARTER`, `LAST_QUARTER`, `NEXT_QUARTER` | One calendar quarter |
| `THIS_YEAR`, `LAST_YEAR`, `NEXT_YEAR` | One calendar year |
| `THIS_FISCAL_QUARTER`, `THIS_FISCAL_YEAR` (and `LAST_` / `NEXT_` forms) | Based on the org's fiscal year settings |
The week literals depend on the running user's locale, because the first day of the week differs between locales. The fiscal literals depend on the org's fiscal year setting, which may be a standard or a custom fiscal year.
Literals that take a number
These have the form KEYWORD:n, where n is a whole number written directly in the query.
| Literal | Meaning |
|---|---|
| `LAST_N_DAYS:n` | From the start of the day `n` days ago up to now. Includes today. |
| `NEXT_N_DAYS:n` | The `n` days after today. Starts tomorrow. |
| `N_DAYS_AGO:n` | The single day that was `n` days ago |
| `LAST_N_WEEKS:n`, `NEXT_N_WEEKS:n`, `N_WEEKS_AGO:n` | The same patterns in weeks |
| `LAST_N_MONTHS:n`, `NEXT_N_MONTHS:n`, `N_MONTHS_AGO:n` | The same patterns in months |
| `LAST_N_QUARTERS:n`, `NEXT_N_QUARTERS:n`, `N_QUARTERS_AGO:n` | The same patterns in quarters |
| `LAST_N_YEARS:n`, `NEXT_N_YEARS:n`, `N_YEARS_AGO:n` | The same patterns in years |
Fiscal versions exist as well, such as LAST_N_FISCAL_QUARTERS:n.
// Cases created in the last 7 days, including today
List<Case> newCases = [
SELECT Id, Subject, CreatedDate
FROM Case
WHERE CreatedDate = LAST_N_DAYS:7
];
// Tasks due in the next 14 days
List<Task> upcoming = [
SELECT Id, Subject, ActivityDate
FROM Task
WHERE ActivityDate = NEXT_N_DAYS:14
AND IsClosed = false
];
System.debug(newCases.size() + ' new cases, ' + upcoming.size() + ' upcoming tasks');Notice that LAST_N_DAYS:7 and N_DAYS_AGO:7 are different. The first is a seven-day range ending now. The second is only the one day, seven days ago.
flowchart TD
A[Need a date filter] --> B{Is the range relative to today?}
B -- Yes --> C{Is the number of units fixed in the query?}
C -- Yes --> D[Use a date literal, such as LAST_N_DAYS:30]
C -- No --> E[Compute a Date or Datetime in Apex and bind it]
B -- No --> F[Bind a Date or Datetime variable, or write a fixed value]The diagram above is not a valid diagram block. Here is the same flow in the required form:
Literals and time zones
A date literal used against a Datetime field is resolved in the running user's time zone. CreatedDate = TODAY covers midnight to midnight in that user's time zone, not UTC. Two users in different zones can therefore get different results from the same query at the same moment.
A fixed Datetime value written with Z is always UTC. If you need the user's calendar day, prefer a literal. If you need an exact moment, write the value with its offset.
Bind variables with dates
Date literals cannot take a bind variable. LAST_N_DAYS::days is not valid. When the number comes from a variable, compute the boundary in Apex and bind that.
Integer days = 30;
Date cutoffDate = Date.today().addDays(-days);
Datetime cutoffTime = Datetime.now().addDays(-days);
List<Opportunity> oldOpps = [
SELECT Id, Name, CloseDate
FROM Opportunity
WHERE CloseDate < :cutoffDate
];
List<Account> newAccounts = [
SELECT Id, Name, CreatedDate
FROM Account
WHERE CreatedDate >= :cutoffTime
];
System.debug(oldOpps.size() + ' old, ' + newAccounts.size() + ' new');Match the type to the field. Bind a Date to a Date field and a Datetime to a Datetime field. This keeps the time-zone behavior obvious.
Date functions
SOQL has functions that pull a part out of a date field. They are useful in WHERE and GROUP BY.
CALENDAR_YEAR(),CALENDAR_QUARTER(),CALENDAR_MONTH()DAY_IN_MONTH(),DAY_IN_WEEK(),WEEK_IN_YEAR()FISCAL_YEAR(),FISCAL_QUARTER()DAY_ONLY(), which returns the date part of a Datetime field
DAY_ONLY() takes the date in the user's time zone. To group by the calendar day on which records were created:
List<AggregateResult> perDay = [
SELECT DAY_ONLY(CreatedDate) day, COUNT(Id) total
FROM Lead
WHERE CreatedDate = LAST_N_DAYS:14
GROUP BY DAY_ONLY(CreatedDate)
ORDER BY DAY_ONLY(CreatedDate)
];
for (AggregateResult ar : perDay) {
System.debug(ar.get('day') + ': ' + ar.get('total'));
}To total opportunity amounts by year:
List<AggregateResult> byYear = [
SELECT CALENDAR_YEAR(CloseDate) yr, SUM(Amount) total
FROM Opportunity
GROUP BY CALENDAR_YEAR(CloseDate)
ORDER BY CALENDAR_YEAR(CloseDate)
];
for (AggregateResult ar : byYear) {
System.debug((Integer) ar.get('yr') + ': ' + ar.get('total'));
}Null dates and common mistakes
- Null dates. A record with no
CloseDateis not matched by any literal or comparison. Use= nullor!= nullto test for it explicitly. - Quoting values.
CloseDate = '2026-11-30'fails. Drop the quotes. - A Date against a Datetime field. Writing
CreatedDate = 2026-11-30fails because the types differ. Use a literal such asYESTERDAY, a full Datetime range, orDAY_ONLY(CreatedDate) = 2026-11-30. LAST_N_DAYSversusN_DAYS_AGO. One is a range and the other is a single day.THIS_WEEKsurprises. The first day of the week follows the user's locale, so a scheduled job and an interactive user can see different weeks.- Dynamic SOQL. In a string passed to
Database.query, literals work as ordinary text. If the number comes from outside, convert it withInteger.valueOf()before concatenating, or compute a boundDateinstead.
Testing date filters
Test data should not depend on today's date being special. Create records relative to Date.today() so the test passes on any day.
CreatedDate is set by the platform. To place a record in the past, call Test.setCreatedDate().
@isTest
private class DateFilterTest {
@isTest
static void findsOnlyRecentAccounts() {
Account recent = new Account(Name = 'Recent');
Account old = new Account(Name = 'Old');
insert new List<Account>{ recent, old };
Test.setCreatedDate(old.Id, Datetime.now().addDays(-40));
List<Account> result = [
SELECT Id, Name FROM Account WHERE CreatedDate = LAST_N_DAYS:30
];
Assert.areEqual(1, result.size());
Assert.areEqual('Recent', result[0].Name);
}
@isTest
static void findsOpportunitiesClosingThisMonth() {
Account a = new Account(Name = 'Test');
insert a;
insert new Opportunity(
Name = 'Closing now',
AccountId = a.Id,
StageName = 'Prospecting',
CloseDate = Date.today()
);
List<Opportunity> result = [
SELECT Id FROM Opportunity WHERE CloseDate = THIS_MONTH
];
Assert.areEqual(1, result.size());
}
}Exercise
A report must list contacts created in the last N days, where N is read from a custom setting at run time and stored in an Integer variable n. Why does WHERE CreatedDate = LAST_N_DAYS::n not work, and what should you write instead?
Show answer
Date literals are keywords fixed in the query text, so a bind variable cannot supply the number. Compute the boundary in Apex with Datetime cutoff = Datetime.now().addDays(-n); and query WHERE CreatedDate >= :cutoff. Because the cutoff is "now minus n days", this differs slightly from LAST_N_DAYS:n, which starts at midnight at the start of the day n days ago. To match it exactly, use Datetime.newInstance(Date.today().addDays(-n), Time.newInstance(0, 0, 0, 0)).
Exercise
What is the difference between CreatedDate = LAST_N_DAYS:3 and CreatedDate = N_DAYS_AGO:3?
Show answer
LAST_N_DAYS:3 covers the range from the start of the day three days ago up to the current moment, so it includes today. N_DAYS_AGO:3 covers only the single day that was three days ago.