Salesforce Apex has a Time class that provides methods for creating Time instances, manipulating and comparing Time. The class represents the local time of day, independent of the date. Here is a detailed tutorial on how to use the Salesforce Time class:
Creating Time Instances
The Time class has a constructor that allows you to create Time instances. Here’s how to create a new Time instance:
Time myTime = Time.newInstance(15, 30, 45, 0); // 15:30:45.0 System.debug(myTime); // DEBUG|15:30:45.000Z
In the Time.newInstance()
method, the parameters represent hours, minutes, seconds, and milliseconds respectively.
Getting Time Components
Once you have a Time instance, you can get the hours, minutes, seconds, and milliseconds components. Here is how to do it:
Integer hours = myTime.hour(); System.debug(hours); // DEBUG|15 Integer minutes = myTime.minute(); System.debug(minutes); // DEBUG|30 Integer seconds = myTime.second(); System.debug(seconds); // DEBUG|45 Integer milliseconds = myTime.millisecond(); System.debug(milliseconds); // DEBUG|0
Comparing Times
The Time class allows you to compare two Time instances using methods like equals()
, before()
, and after()
. Here’s how to use them:
Time time1 = Time.newInstance(12, 0, 0, 0); Time time2 = Time.newInstance(15, 30, 45, 0); Boolean isEqual = time1.equals(time2); System.debug(isEqual); // DEBUG|false Boolean isBefore = time1.before(time2); System.debug(isBefore); // DEBUG|true Boolean isAfter = time1.after(time2); System.debug(isAfter); // DEBUG|false
Adding and Subtracting Time
Here’s are a couple of examples:
// Adding time Time myTime = Time.newInstance(1, 2, 3, 4); Time expected = Time.newInstance(4, 2, 3, 4); System.assertEquals(expected, myTime.addHours(3)); // Subtracting time Time myTime = Time.newInstance(1, 2, 55, 0); Time expected = Time.newInstance(1, 3, 5, 0); System.assertEquals(expected, myTime.addSeconds(-10));
Schedule Apex in Salesforce: A Technical Guide for Developers
Salesforce Apex security best practices
Speeding Up Apex Test Execution: A Guide for Faster Salesforce Deployments