Working with DateTime
in Apex can be challenging, especially when converting DateTime
values to other time zones to extract the time part only. Many built-in Salesforce methods, like String.valueOf
, automatically convert DateTime
values to the user’s local time zone. This can make testing and debugging difficult, as System.debug
displays the time in the user’s time zone rather than the original or intended time zone, making it tricky to verify if conversions were done as expected.
The following Apex code converts the current DateTime
to a specific time zone such as America/New_York
and then converts it to a string without altering it to the user’s local time zone. The string DateTime
is then parsed into separate variables to extract the date and time components.
//DateTime.now returns the current Datetime based on GMT calendar
Datetime currentGmtTime = DateTime.now();
// Get the time zone
TimeZone tz = TimeZone.getTimeZone('America/New_York');
integer offset = tz.getOffset(currentGmtTime);
// Convert the GMT time to the timezone of operating hour
Datetime currentDateTime = currentGmtTime.addSeconds((offset / 1000));
system.debug('currentGmtTime::'+currentGmtTime);
System.debug('Current datetime in America/New_York: ' + currentDateTime );
//Convert datetime to string by concatenating blank space, this approach does not convert the time to local time. Using String.valueOf method converts the datetime to user local time
String currentDateTimeStr = ''+currentDateTime;
// Split the formatted datetime string and create a Time instance
//Example datetime = 2024-11-08 01:45:49
List<String> DatetimeParts = currentDateTimeStr.split(' ');
List<String> DateParts = DatetimeParts[0].split('-');
List<String> timeParts = DatetimeParts[1].split(':');
Integer year = Integer.valueOf(DateParts[0]);
Integer month = Integer.valueOf(DateParts[1]);
Integer day = Integer.valueOf(DateParts[2]);
Integer hours = Integer.valueOf(timeParts[0]);
Integer minutes = Integer.valueOf(timeParts[1]);
Integer seconds = Integer.valueOf(timeParts[2]);
system.debug('hours::'+hours);
system.debug('minutes::'+minutes);
Time currentTime = Time.newInstance(hours, minutes, seconds, 0);
System.debug('Time in America/New_York timezeon :'+currentTime );
Date currentDate = Date.newInstance(year, month, day);
System.debug('Date in America/New_York timezeon :'+currentDate );