In Apex, the Time data type is used to represent time values without a date component. It stores time values in the format HH:mm:ss.SSS, where HH represents hours in 24-hour format, mm represents minutes, ss represents seconds, and SSS represents milliseconds. The Time data type is commonly used for scenarios where you need to work with time-of-day information independently of dates. Here's an example of how to declare and use a Time variable in Apex:
public class TimeExample {
public static void main() {
Time currentTime = Time.now();
Time lunchTime = Time.newInstance(12, 0, 0, 0);
System.debug('Current Time: ' + currentTime);
System.debug('Lunch Time: ' + lunchTime);
// Comparing times
if (currentTime > lunchTime) {
System.debug('It's past lunchtime.');
} else {
System.debug('It's not yet lunchtime.');
}
}
}
We declare a Time variable currentTime and initialize it with the current time using the Time.now() method.
We create a Time variable lunchTime and set it to 12:00:00.
We use System.debug() to print the values of currentTime and lunchTime to the debug log.
We use an if statement to compare the times. If currentTime is after lunchTime, we print a message indicating that it's past lunchtime. Otherwise, we print a message indicating that it's not yet lunchtime.