0

I have a public Visualforce page on Salesforce Sites with the form below.

enter image description here

The site Guest user expects the event to be created in their time zone (EST) for the same date and time as it appears on the page.

What actually happens on the server side is the appointment date and time are the same but in the GMT time zone.

So in this case, the Guest sees '07/04/2021 04:00 PM'

but on the server, the value of AppointmentDate is '2021-07-04T16:00:00.000Z' (GMT)

The page's custom controller:

public class MyEventController {
  public MyEventController() {
  }

  public Datetime AppointmentDate { get; set; }

  public Pagereference Save() {
    Event event = new Event(Subject = 'New Event');
    event.Type = 'Meeting';
    event.Location = '123 main st';
    event.StartDateTime = this.AppointmentDate;
    event.EndDateTime = this.AppointmentDate; 
    insert event;
    return null;
  }
}

After the event is inserted, the event shows on the Salesforce calendar at 12:00 PM (EST).

What has to be done so that my code inserts the Event at the same date and time as the Guest user sees on the page? (Please be specific)

Thank you

3

All time zones in Salesforce are GMT in the backend. You will need to utilize the TimeZone class to correct for this. After all, your visitor might be coming from anywhere in the world, even if it is EST. To fix this, select the appropriate TimeZone from the class:

TimeZone easternTimeZone = TimeZone.getTimeZone('America/New_York');

Then subtract that time from the GMT:

DateTime appointmentTimeInGmt = this.AppointmentDate.addSeconds(
  -easternTimeZone.getOffset(this.AppointmentDate)/1000
);

The reason why we subtract the time offset, instead of adding it, is because we're "undoing" the effect of GMT calculation (e.g. to get from GMT to EST, we subtract five hours, so to "undo" it, we have to add five hours). The reason why we divide by 1000 is because the offset is in milliseconds, but we can't add milliseconds, only seconds, so we do a conversion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.