Sub topic 7
Dates, times, and datetimes
Apex has three types for points in time: Date, Time, and Datetime. This chapter assumes you know how to declare variables and call methods on them, and that you have seen null handling from earlier chapters. The main skill here is knowing which of the three types fits a value, and where time zones change results.
The three types
| Type | Holds | Time zone aware | Typical Salesforce field |
|---|---|---|---|
| `Date` | Year, month, day | No | Date |
| `Time` | Hour, minute, second, millisecond | No | Time |
| `Datetime` | A date and a time, stored as an instant | Yes | Date/Time |
A Date is a calendar day. It is the same day for every user. A Datetime is a moment in time. Salesforce stores it in GMT and shows it in each user's time zone. Mixing the two is the main source of date bugs.
Date
Create a Date with Date.newInstance(year, month, day) or Date.today(). Use Date.valueOf('2026-11-30') to parse the yyyy-MM-dd format.
Date start = Date.newInstance(2026, 11, 30);
Date due = start.addDays(14);
System.debug(due.year() + '-' + due.month() + '-' + due.day()); // 2026-12-14
System.debug(start.daysBetween(due)); // 14
System.debug(due > start); // true
System.debug(Date.valueOf('2026-02-01').month()); // 2Calling a.daysBetween(b) returns a positive number when b is later than a. The comparison operators <, >, <=, >=, and == work directly on dates.
Month arithmetic clamps to the last valid day:
Date jan31 = Date.newInstance(2026, 1, 31);
Date feb = jan31.addMonths(1);
System.debug(feb.day()); // 28, not 31Other useful Date methods:
toStartOfMonth()andtoStartOfWeek()return the first day of the month or week. The week start depends on the user's locale.Date.daysInMonth(2026, 2)andDate.isLeapYear(2028)are static methods.monthsBetweencounts whole months. January 31 to February 1 is 0.
An impossible date such as Date.newInstance(2026, 13, 1) throws a runtime exception. Validate input that comes from users or integrations before building dates from it.
Time
A Time has no date and no time zone. Create one with Time.newInstance(hour, minute, second, millisecond). All four arguments are required.
Time opens = Time.newInstance(9, 30, 0, 0);
Time later = opens.addHours(2).addMinutes(15);
System.debug(later.hour()); // 11
System.debug(later.minute()); // 45
System.debug(later > opens); // trueTime is wall-clock time, so addHours can wrap past midnight. Time.newInstance(23, 0, 0, 0).addHours(2) gives 01:00. Nothing records that a day boundary was crossed.
Datetime
A Datetime represents an instant. Several constructors exist, and they differ in which time zone they assume:
| Method | Interprets the arguments as |
|---|---|
| `Datetime.now()` | The current moment |
| `Datetime.newInstance(y, m, d, h, mi, s)` | The running user's time zone |
| `Datetime.newInstanceGmt(y, m, d, h, mi, s)` | GMT |
| `Datetime.newInstanceGmt(date, time)` | GMT |
| `Datetime.valueOf('2026-11-30 12:00:00')` | The running user's time zone |
| `Datetime.valueOfGmt('2026-11-30 12:00:00')` | GMT |
Choose the Gmt variants when you need a result that does not depend on who runs the code. This matters for tests and for scheduled jobs.
Datetime dt = Datetime.newInstanceGmt(2026, 11, 30, 23, 30, 0);
System.debug(dt.formatGmt('yyyy-MM-dd HH:mm')); // 2026-11-30 23:30
System.debug(dt.format('yyyy-MM-dd HH:mm', 'Asia/Tokyo')); // 2026-12-01 08:30
System.debug(dt.addHours(1).formatGmt('yyyy-MM-dd HH:mm')); // 2026-12-01 00:30
System.debug(dt.dateGmt().day()); // 30
System.debug(dt.getTime()); // milliseconds since 1970-01-01 GMTThe same instant shows a different calendar day in Tokyo than in GMT. The pair dateGmt() and timeGmt() split a Datetime using GMT. The pair date() and time() split it using the running user's time zone, so the result can change between users.
format() with no arguments uses the user's locale and time zone. Passing a pattern and a time zone ID, as above, makes the output predictable.
Combining and converting
To build a Datetime from separate parts, pass a Date and a Time:
Date day = Date.newInstance(2026, 12, 25);
Time at = Time.newInstance(18, 0, 0, 0);
Datetime event = Datetime.newInstanceGmt(day, at);
System.debug(event.formatGmt('EEE yyyy-MM-dd HH:mm')); // Fri 2026-12-25 18:00Going the other way, Date.newInstance(...) does not accept a Datetime, so call dt.date() or dt.dateGmt().
Null and common errors
Each of these types is a reference to an object, so an unset variable is null. Calling a method on it throws a NullPointerException. Combine the ?. and ?? operators from earlier chapters with date values:
Date renewal = null;
Integer year = renewal?.year() ?? 0;
System.debug(year); // 0Mistakes to watch for:
- Comparing a
Dateand aDatetimeby hand. Convert both to one type first. Comparedt.dateGmt()with theDate, not the other way round. - Using
date()near midnight. ADatetimelate in the evening in one time zone is already the next day in another. Decide whether you mean the user's day or the GMT day. - Parsing with
Date.parse. It reads the current user's locale format, such as12/25/2026or25/12/2026. UseDate.valueOffor ISO strings. - Subtracting dates with
-. UsedaysBetween. For aDatetimedifference, subtract thegetTime()values and divide by 86,400,000 for days. - Expecting
addMonthsto be reversible. Adding a month and then subtracting one does not always return the original day.
Exercise
Using only the methods in this chapter, write Apex that prints how many whole days remain between a fixed date of 2026-11-30 and the end of that year (2026-12-31), then prints the date one month after 2026-01-31 as year-month-day. What do the two lines print?
Show answer
Code: Date a = Date.newInstance(2026, 11, 30); Date b = Date.newInstance(2026, 12, 31); System.debug(a.daysBetween(b)); Date c = Date.newInstance(2026, 1, 31).addMonths(1); System.debug(c.year() + '-' + c.month() + '-' + c.day());. The first line prints 31. The second prints 2026-2-28, because addMonths clamps to the last valid day of February.
Exercise
A Datetime is created with Datetime.newInstanceGmt(2026, 6, 1, 23, 0, 0). A user in the Asia/Tokyo time zone (UTC+9) and a user in GMT each call date()-style logic on it. Which calendar day does each see, and which method guarantees the same answer for both?
Show answer
The GMT user sees June 1. The Tokyo user sees June 2, because 23:00 GMT is 08:00 the next morning in Tokyo. dateGmt() returns June 1 for both users, because it always splits the value using GMT.