Strings, Dates & Math

For business-day calculations use the BusinessHours class (BusinessHours.add(bhId, start, millis), BusinessHours.isWithin(bhId, dt)), which respects the org's configured business hours and holidays.

9.1 String methods

'Apex'.toUpperCase() / toLowerCase() 'APEX' / 'apex' ' hi '.trim()

'Hello'.startsWith('He') / endsWith('lo') 'Hello'.substring(1, 3) ('a', 'b', 'c') String.join(list, ', ') 'Hello'.replace('l', 'L') 'a1b2'.replaceAll('[0-9]', '') 'ab' (regex) '7'.leftPad(3, '0') 'long text here'.abbreviate(8) String.isBlank(s) / isNotBlank(s) Null-safe blank checks true for null or '' (but not ' ')

String.format('{0} has {1} items', new List<Object>{ 'Cart', 3 }) 'Cart has 3 items' Escapes ' for dynamic SOQL

String csv = 'Ada,Lovelace,[email protected]';
List<String> parts = csv.split(',');
String fullName = parts[0] + ' ' + parts[1];

// regular expressions
Pattern p = Pattern.compile('^[A-Z]{3}-[0-9]{4}$');
Matcher m = p.matcher('INV-2025');
System.debug(m.matches());   // true

// multi-line strings: use concatenation or escape sequences
String body = 'Line 1\nLine 2\tTabbed';

9.2 Dates, Datetimes, and Times

For business-day calculations use the BusinessHours class (BusinessHours.add(bhId, start, millis), BusinessHours.isWithin(bhId, dt)), which respects the org's configured business hours and holidays.

Date today = Date.today();
Date nextWeek = today.addDays(7);
Date endOfMonth = today.toStartOfMonth().addMonths(1).addDays(-1);
Integer daysLeft = today.daysBetween(endOfMonth);
Integer monthDays = Date.daysInMonth(2028, 2);        // 29
Boolean leap = Date.isLeapYear(2028);
Date custom = Date.newInstance(2025, 12, 31);
Date weekStart = today.toStartOfWeek();               // locale-dependent

Datetime now = Datetime.now();                        // GMT internally
String formatted = now.format('yyyy-MM-dd HH:mm');    // in the running user's time zone
String iso = now.formatGmt('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
Datetime later = now.addHours(3);
Date justDate = now.date();
Long millis = now.getTime();
Datetime gmt = Datetime.newInstanceGmt(2025, 1, 15, 12, 0, 0);

Time t = Time.newInstance(17, 30, 0, 0);

9.3 Math and Decimal

Decimal keeps scale (trailing zeros), which matters for currency: Decimal.valueOf('1.50').scale() is 2.

Decimal price = 19.995;
Decimal rounded = price.setScale(2, RoundingMode.HALF_UP);   // 20.00
Decimal down    = price.setScale(2, RoundingMode.DOWN);      // 19.99

Integer biggest = Math.max(4, 9);
Decimal absVal  = Math.abs(-3.5);
Double root     = Math.sqrt(16);
Double power    = Math.pow(2, 10);       // 1024.0
Long roundedL   = Math.roundToLong(2.5); // 3
Double rnd      = Math.random();         // [0, 1)
Integer dice    = (Integer) Math.floor(Math.random() * 6) + 1;
Integer r       = Math.mod(10, 3);       // 1
Decimal ceiling = Math.ceil(4.1);        // 5