Sub topic 2
Dates, Times, and Datetimes in Apex
Assume you know variables, expressions, conditionals, and basic Salesforce objects. This chapter focuses on choosing types and reading Apex code that combines them.
Dates, times, and datetimes
A Date stores a calendar date without a time zone. A Time stores a time of day. A Datetime stores both a date and a time.
Date today = Date.today();
Date launchDate = Date.newInstance(2026, 12, 1);
Time opening = Time.newInstance(9, 30, 0, 0);
Datetime createdAt = Datetime.now();
System.debug(launchDate);
System.debug(opening);
System.debug(createdAt);Use Date for birthdays or due dates. Use Datetime for events that occur at a specific moment. Be careful when converting datetimes because time zones can affect the displayed value.
Constants and variable scope
A constant is a value that cannot be reassigned. Declare it with final.
final Integer MAX_RETRIES = 3;
Integer attempts = 0;
attempts += 1;A local variable is visible from its declaration to the end of its block. A class variable is visible according to its access modifier and can be shared by methods in that class. Keep variables in the smallest scope that needs them.
Lists, sets, and maps
A List preserves order and allows duplicates. A Set stores unique values. A Map associates keys with values.
List<String> names = new List<String>{ 'Ava', 'Kai' };
Set<String> regions = new Set<String>{ 'West', 'West' };
Map<Id, Account> accountsById = new Map<Id, Account>();
System.debug(names.size()); // 2
System.debug(regions.size()); // 1SObjects as data types
An SObject type represents a Salesforce record, such as Account or Contact.
Account accountRecord = new Account(Name = 'Acme');
List<Account> accounts = new List<Account>{ accountRecord };The record is only in memory until you insert it with DML.
Enums for fixed value sets
An enum defines a closed set of named values.
public enum Priority { LOW, MEDIUM, HIGH }
Priority current = Priority.HIGH;
System.debug(current == Priority.HIGH);Enums prevent unrelated strings from being accepted accidentally.
Converting and casting
A cast tells Apex to treat an existing value as a compatible type. A valueOf method parses text into a typed value.
Object raw = '42';
String text = (String) raw;
Integer number = Integer.valueOf(text);
Long largerNumber = number;
Id recordId = Id.valueOf('001000000000001AAA');
System.debug(largerNumber);Implicit widening can move an Integer to a Long or Decimal. The reverse conversion requires an explicit method and may lose information.
Exercise
Which type should represent a meeting scheduled for an exact moment: Date, Time, or Datetime?
Show answer
Datetime, because it stores both the calendar date and time.