Skip to main content
2 of 5
added 68 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 (Note note, 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 string of the user by:

UserInfo.getTimeZone();

Then add the offset to your datetime:

d.addHours(the offest);
Jesse Milburn
  • 2.7k
  • 1
  • 18
  • 35