Skip to main content
5 of 5
added 55 characters in body
Jesse Milburn
  • 2.7k
  • 1
  • 18
  • 35

You need to calculate the offset of the time element of your Datetime object.

Note the second parameter is the Timezone id, not a SF id but a Timezone.getId()

public static Integer timeZoneOffset_hours(Date d, String timezoneId) {
    TimeZone tzSelected = TimeZone.getTimeZone(timezoneId);
    TimeZone tzGmt = TimeZone.getTimeZone('Greenwich Mean Time');

    Integer gmtOffset = tzGmt.getOffset(d);
    Integer selectedOffset = tzSelected.getOffset(d);
    Integer hours = (selectedOffset - gmtOffset) / 1000 / 60 / 60; 

    return hours;
}

Using this you can pass the date portion of your datetime object and the timezone you wish to convert to.

You can easily get the timezone id of the user to pass into the method:

UserInfo.getTimeZone().getId();

Then add the offset returned by the method to your datetime:

d.addHours(the offest);

Then format that value for the date.

Jesse Milburn
  • 2.7k
  • 1
  • 18
  • 35