Date
Learning Content
Last updated: July 28, 2026
Date Data Type
The Date data type is used to store a calendar date without any time information. It represents values such as birthdays, order dates, contract expiry dates, invoice dates, and Opportunity Close Dates.
Unlike the DateTime data type, a Date stores only the year, month, and day. It does not include hours, minutes, seconds, or time zone information.
The Date data type provides several built-in methods that make it easy to create dates, calculate future or past dates, determine differences between dates, and perform common business calculations.
💡 LearnFrenzy Insight
Think about your birthday. For example:
- 15 August 1995
- 01 January 2026
- 31 December 2026
Your birthday represents only a calendar date. It doesn't matter whether you were born at 8:00 AM or 6:30 PM for many business scenarios. This is exactly what the Date data type stores.
What is a Date?
A Date represents a calendar day consisting of the year, month, and day. It does not contain any time or time zone information. In Apex, Date is a system-defined class with built-in methods for date manipulation.
Date today = Date.today();
Date projectStart = Date.newInstance(2026, 7, 27);
Date specificDate = Date.valueOf('2026-07-27');
Date nullDate; // Declaration without initialization
System.debug(today);
System.debug(projectStart);
System.debug(specificDate);
💡 Pro Tip: Use Date.valueOf('YYYY-MM-DD') to parse dates from strings in a standard format. This is especially useful when working with external systems or user input.
Why Use Date?
| Reason | Benefit |
|---|---|
| Calendar Values | Stores only the date without time for cleaner data |
| Business Scheduling | Tracks orders, contracts, renewals, and milestones |
| Date Calculations | Add or subtract days with built-in methods like addDays() |
| Reporting | Commonly used in Salesforce reports and dashboards |
| Validation Rules | Ideal for checking date ranges and deadlines |
| Automation | Used in workflows, process builder, and flows |
Creating Date Values
There are several ways to create Date values in Apex:
1. Current Date
Date today = Date.today();
System.debug('Today\'s Date: ' + today);
2. Create a Specific Date
Date releaseDate = Date.newInstance(2026, 12, 31);
System.debug('Release Date: ' + releaseDate);
3. Parse from String
Date fromString = Date.valueOf('2026-12-31');
System.debug('Parsed Date: ' + fromString);
4. Create from Components
Integer year = 2026;
Integer month = 7;
Integer day = 27;
Date customDate = Date.newInstance(year, month, day);
System.debug('Custom Date: ' + customDate);
5. Create from DateTime
DateTime now = DateTime.now();
Date fromDateTime = now.date();
System.debug('Date from DateTime: ' + fromDateTime);
📝 Key Points:
- Uninitialized Date variables default to
null. - Always use
YYYY-MM-DDformat when parsing date strings. - Month values are 1-based (January = 1, December = 12).
- Use
Date.today()in the context of the Salesforce user's time zone.
Adding and Subtracting Days, Months, Years
Date today = Date.today();
// Adding days
Date nextWeek = today.addDays(7);
Date nextMonth = today.addDays(30);
// Subtracting days
Date previousWeek = today.addDays(-7);
Date previousMonth = today.addDays(-30);
// Adding months
Date nextMonthDate = today.addMonths(1);
Date nextYearDate = today.addMonths(12);
// Adding years
Date nextYear = today.addYears(1);
Date previousYear = today.addYears(-1);
// Chaining methods
Date futureDate = today.addDays(10).addMonths(1).addYears(1);
System.debug('Next Week: ' + nextWeek);
System.debug('Previous Week: ' + previousWeek);
System.debug('Next Month: ' + nextMonthDate);
System.debug('Next Year: ' + nextYear);
System.debug('Future Date: ' + futureDate);
💡 Pro Tip: Methods like addDays(), addMonths(), and addYears() are chainable, allowing you to combine multiple date operations in one line.
Finding the Difference Between Two Dates
Date startDate = Date.newInstance(2026, 7, 1);
Date endDate = Date.newInstance(2026, 7, 31);
Integer days = startDate.daysBetween(endDate);
Integer months = startDate.monthsBetween(endDate);
System.debug('Days Between: ' + days); // 30
System.debug('Months Between: ' + months); // 0
// Example with different months
Date start = Date.newInstance(2026, 1, 15);
Date end = Date.newInstance(2026, 3, 20);
Integer daysDiff = start.daysBetween(end);
Integer monthsDiff = start.monthsBetween(end);
System.debug('Days Between Jan 15 and Mar 20: ' + daysDiff); // 64
System.debug('Months Between Jan 15 and Mar 20: ' + monthsDiff); // 2
Output
Days Between: 30 Months Between: 0 Days Between Jan 15 and Mar 20: 64 Months Between Jan 15 and Mar 20: 2
⚠️ Important: daysBetween() returns the number of days between two dates. monthsBetween() returns the approximate number of months. For precise day counts, always use daysBetween().
Useful Date Methods
| Method | Description | Example | Result |
|---|---|---|---|
Date.today() | Returns today's date | Date.today() | 2026-07-27 |
Date.newInstance() | Creates a specific date | Date.newInstance(2026,7,27) | 2026-07-27 |
Date.valueOf() | Parses a date from string | Date.valueOf('2026-07-27') | 2026-07-27 |
addDays() | Adds or subtracts days | today.addDays(10) | 2026-08-06 |
addMonths() | Adds or subtracts months | today.addMonths(1) | 2026-08-27 |
addYears() | Adds or subtracts years | today.addYears(1) | 2027-07-27 |
daysBetween() | Returns days between dates | date1.daysBetween(date2) | 30 |
monthsBetween() | Returns months between dates | date1.monthsBetween(date2) | 2 |
year() | Extracts year from date | today.year() | 2026 |
month() | Extracts month from date | today.month() | 7 |
day() | Extracts day from date | today.day() | 27 |
isSameDay() | Checks if two dates are the same day | date1.isSameDay(date2) | true/false |
format() | Formats date as string | today.format() | 2026-07-27 |
Extracting Date Components
Date today = Date.today();
// Extract individual components
Integer year = today.year();
Integer month = today.month();
Integer day = today.day();
System.debug('Year: ' + year);
System.debug('Month: ' + month);
System.debug('Day: ' + day);
// Get day of week
Integer dayOfWeek = today.toStartOfWeek().daysBetween(today);
// 0 = Sunday, 1 = Monday, etc.
// Check if date is in the future
Boolean isFuture = today > Date.today();
// Check if date is in the past
Boolean isPast = today < Date.today();
// Check if dates are equal
Date tomorrow = Date.today().addDays(1);
Boolean isEqual = today == tomorrow; // false
Output
Year: 2026 Month: 7 Day: 27
Real Salesforce Business Examples
🏢 Business Scenario 1: Product Warranty Calculation
A company offers a 30-day product warranty from the purchase date.
Date purchaseDate = Date.today();
Date warrantyExpiry = purchaseDate.addDays(30);
Integer daysRemaining = Date.today().daysBetween(warrantyExpiry);
System.debug('Purchase Date: ' + purchaseDate);
System.debug('Warranty Expiry: ' + warrantyExpiry);
System.debug('Days Remaining: ' + daysRemaining);
// Check if warranty is still valid
if (Date.today() <= warrantyExpiry) {
System.debug('Product is under warranty.');
} else {
System.debug('Product is out of warranty.');
}
Output
Purchase Date: 2026-07-27 Warranty Expiry: 2026-08-26 Days Remaining: 30 Product is under warranty.
🏢 Business Scenario 2: Contract Renewal Date
Calculate the renewal date for an annual contract.
Date contractStart = Date.newInstance(2026, 1, 1);
Integer contractDurationMonths = 12;
Date contractEnd = contractStart.addMonths(contractDurationMonths);
Date renewalDate = contractEnd.addDays(30); // 30 days grace period
System.debug('Contract Start: ' + contractStart);
System.debug('Contract End: ' + contractEnd);
System.debug('Renewal Date: ' + renewalDate);
// Check if renewal is approaching (within 30 days)
Date today = Date.today();
Integer daysUntilRenewal = today.daysBetween(renewalDate);
if (daysUntilRenewal <= 30 && daysUntilRenewal > 0) {
System.debug('Renewal is approaching in ' + daysUntilRenewal + ' days.');
} else if (daysUntilRenewal <= 0) {
System.debug('Contract is up for renewal or overdue.');
}
Output
Contract Start: 2026-01-01 Contract End: 2027-01-01 Renewal Date: 2027-01-31
🏢 Business Scenario 3: Age Calculation
Calculate the age of a person or asset based on a birth date.
Date birthDate = Date.newInstance(1990, 8, 15);
Date currentDate = Date.today();
// Calculate age in years
Integer ageYears = birthDate.monthsBetween(currentDate) / 12;
Integer ageDays = birthDate.daysBetween(currentDate);
// Calculate next birthday
Date nextBirthday = Date.newInstance(currentDate.year(), birthDate.month(), birthDate.day());
if (nextBirthday < currentDate) {
nextBirthday = nextBirthday.addYears(1);
}
Integer daysUntilBirthday = currentDate.daysBetween(nextBirthday);
System.debug('Birth Date: ' + birthDate);
System.debug('Current Age (Years): ' + ageYears);
System.debug('Current Age (Days): ' + ageDays);
System.debug('Next Birthday: ' + nextBirthday);
System.debug('Days Until Next Birthday: ' + daysUntilBirthday);
Output
Birth Date: 1990-08-15 Current Age (Years): 35 Current Age (Days): 13146 Next Birthday: 2026-08-15 Days Until Next Birthday: 19
Date Formatting
Date today = Date.today();
// Default format (YYYY-MM-DD)
String defaultFormat = String.valueOf(today);
System.debug('Default: ' + defaultFormat); // 2026-07-27
// Custom formatting using DateTime
DateTime dt = DateTime.newInstance(today, Time.newInstance(0, 0, 0, 0));
String formatted = dt.format('MMMM dd, yyyy');
System.debug('Formatted: ' + formatted); // July 27, 2026
// Using String.format
String custom = String.format('{0,date,dd-MMM-yyyy}', new List<object>{dt});
System.debug('Custom: ' + custom); // 27-Jul-2026
// Alternative formatting
String yearMonth = today.year() + '-' + String.valueOf(today.month()).leftPad(2, '0');
System.debug('Year-Month: ' + yearMonth); // 2026-07
Output
Default: 2026-07-27 Formatted: July 27, 2026 Custom: 27-Jul-2026 Year-Month: 2026-07
Date Validation & Comparison
Date today = Date.today();
Date startDate = Date.newInstance(2026, 1, 1);
Date endDate = Date.newInstance(2026, 12, 31);
// Check if a date is within a range
Boolean isInRange = today >= startDate && today <= endDate;
System.debug('Is today in 2026? ' + isInRange); // true
// Check if date is in the future
Boolean isFutureDate = today > Date.today();
System.debug('Is today in future? ' + isFutureDate); // false
// Check if date is in the past
Boolean isPastDate = today < Date.today();
System.debug('Is today in past? ' + isPastDate); // false
// Check if two dates are the same day
Date tomorrow = today.addDays(1);
Boolean isSameDay = today.isSameDay(tomorrow);
System.debug('Is today same as tomorrow? ' + isSameDay); // false
// Check if a date is valid (not null and in reasonable range)
if (startDate != null && startDate.year() > 1900) {
System.debug('Date is valid');
}
Output
Is today in 2026? true Is today in future? false Is today in past? false Is today same as tomorrow? false Date is valid
Common Date Pitfalls & Solutions
| Pitfall | Example | Solution |
|---|---|---|
| Null Pointer Exception | Date d; Date e = d.addDays(5); |
Always initialize: Date d = Date.today(); or check for null |
| Invalid Date Values | Date.newInstance(2026, 13, 32); |
Validate month (1-12) and day (1-31) before creating |
| Leap Year Handling | Date.newInstance(2024, 2, 29); // Valid (leap year) |
Use built-in methods; they handle leap years automatically |
| Time Zone Confusion | Date.today() vs user's time zone |
Understand that Date.today() uses the context user's time zone |
| String Parsing Issues | Date.valueOf('2026/07/27'); |
Use correct format: Date.valueOf('2026-07-27'); |
| Not Considering Business Days | Adding 5 days always | Custom logic needed for business day calculations (excluding weekends) |
How Salesforce Stores Date Values
Developer Creates Date
Date orderDate = Date.newInstance(2026, 7, 27);
│
▼
Compiler Validates
✔ Year: 2026 (valid)
✔ Month: 7 (1-12)
✔ Day: 27 (valid for month)
│
▼
Date Object Created
2026-07-27
│
▼
Stored in Database
As Date field without time
│
▼
Available for Calculations
Used in Apex code, formulas, and reports
Dates are stored in Salesforce database as date values without time zone information.
Common Salesforce Use Cases
| Business Requirement | Example | Salesforce Object/Field |
|---|---|---|
| Opportunity Close Date | 2026-12-31 | Opportunity.CloseDate |
| Contract Start Date | 2026-01-01 | Contract.StartDate |
| Contract End Date | 2027-01-01 | Contract.EndDate |
| Invoice Date | 2026-07-15 | Invoice__c.Invoice_Date__c |
| Employee Joining Date | 2025-04-10 | Employee__c.Joining_Date__c |
| Warranty Expiry | 2026-08-26 | Product__c.Warranty_Expiry__c |
| Subscription Renewal | 2027-01-31 | Subscription__c.Renewal_Date__c |
| Birth Date | 1990-08-15 | Contact.Birthdate |
| Project Milestone | 2026-09-15 | Project__c.Milestone_Date__c |
🔍 Behind the Scenes: Date Processing
Order Created in System
│
▼
Purchase Date Saved
Date.today() or user input
│
▼
Warranty Calculated
purchaseDate.addDays(30)
│
▼
Renewal Reminder Generated
Using daysBetween() comparison
│
▼
Notification Sent
30 days before expiry
│
▼
Business Process Continues
Workflow, approval, or update
Working with Business Days
Salesforce doesn't have a built-in method for business day calculations, but you can create custom logic:
// Function to add business days (excluding weekends)
public static Date addBusinessDays(Date startDate, Integer businessDays) {
Date current = startDate;
Integer added = 0;
while (added < businessDays) {
current = current.addDays(1);
// Check if it's not Saturday (6) or Sunday (0)
Integer dayOfWeek = current.toStartOfWeek().daysBetween(current);
if (dayOfWeek != 0 && dayOfWeek != 6) {
added++;
}
}
return current;
}
// Usage
Date start = Date.today();
Date end = addBusinessDays(start, 5);
System.debug('Start Date: ' + start);
System.debug('End Date (5 business days): ' + end);
💡 Pro Tip: For advanced business day calculations (including holidays), consider using Salesforce Flow or custom Apex classes with holiday lists.
✅ Best Practices
- Use
Datewhenever time information is not required for the business process. - Prefer built-in methods such as
addDays(),addMonths(),addYears(), anddaysBetween()instead of manual calculations. - Use meaningful variable names such as
startDate,endDate,expiryDate, orrenewalDate. - Always validate date values before using them in logic (check for null).
- Use
Date.valueOf()with standard formatYYYY-MM-DDfor string parsing. - Consider time zones when using
Date.today()in user-facing applications. - Use
isSameDay()for date equality instead of comparing string representations. - Create custom utility methods for complex date calculations (e.g., business days).
⚠️ Common Mistakes
- Using
Datewhen time information is required (useDateTimeinstead). - Manually calculating future dates instead of using built-in
addDays()methods. - Confusing
DatewithDateTimedata types. - Ignoring leap years when writing custom date calculations.
- Forgetting that uninitialized Date variables are
null. - Using incorrect string format when parsing dates with
Date.valueOf(). - Assuming
Date.today()returns the same date for all users (time zone dependent). - Not handling null dates in comparisons or calculations.
🎯 Interview Tip
Question: What is the difference between Date and DateTime in Apex?
Answer: A Date stores only the calendar date (year, month, and day). A DateTime stores both the date and the exact time (hours, minutes, seconds, milliseconds) along with time zone context. Date is ideal for birthdays, due dates, and contract dates, while DateTime is suitable for timestamps, meetings, scheduled jobs, and event tracking.
Question: How do you add 7 days to a Date in Apex?
Answer: Use the addDays() method: Date newDate = currentDate.addDays(7); This returns a new Date object with 7 days added. For subtraction, use negative values: Date pastDate = currentDate.addDays(-7);
Question: How do you calculate the number of days between two dates in Apex?
Answer: Use the daysBetween() method: Integer days = startDate.daysBetween(endDate); This returns the number of days between the two dates. For example, if startDate is 2026-07-01 and endDate is 2026-07-31, the result is 30 days.
📌 Quick Revision
- ✔ Stores only the calendar date (year, month, day).
- ✔ Does not include time or time zone information.
- ✔ Create dates using
Date.today(),Date.newInstance(), orDate.valueOf(). - ✔ Supports built-in methods:
addDays(),addMonths(),addYears(),daysBetween(),monthsBetween(). - ✔ Extract components:
year(),month(),day(). - ✔ Commonly used for Opportunity Close Dates, contract dates, invoices, warranties, and subscriptions.
- ✔ Use
DateTimeinstead when time information is required. - ✔ Uninitialized Date variables default to
null. - ✔ Use
isSameDay()for date equality checks. - ✔
Date.today()is time zone dependent (uses the context user's time zone).
➡ Next Lesson
In the next lesson, you'll explore the DateTime data type in detail. You'll learn:
- How Apex stores both date and time values together.
- Understanding time zones and how they affect DateTime calculations.
- Creating DateTime values from dates, times, and strings.
- Common DateTime methods for manipulation and formatting.
- Working with timestamps in Salesforce applications (e.g., audit fields, scheduled jobs).
- Converting between Date and DateTime for different use cases.
Practice What You've Learned
Test your understanding with these practice exercises