[SalesForce] DateTime conversion to time zone

I want to save event in picked timezone. So the cese is:
If user location Moscow, he want to create meeting in London, he checks picklist London. And the event must be saved in London time. For example He picks London and time 20:00. After save it will be 22:00 by Moscow standard time. How can it be accomplished?

I tried it in different ways:

  1. Through date parse – no results
  2. By changing current user locale – from time to time it works

This is the save button:

public PageReference save() {

    //Custom validation errors
    try{  
        ChangeTimeZone(); // here I try to set the the local timezone to get current value of datetime                            
        //creating the event after there are no error messages                   
        Event ev = (Event)stdcontroller.getRecord();      
        **ev.ActivityDateTime = m_repository.parse(startDate, startHour); // Here I try to parse datetime to get the local time.
        //****
        insert ev;                                

        //Save standard fields         
        stdController.save();
        ChangeTimeZoneBack(); //here I try to set back current user timezone

        //return page reference            
        String explicitReturnUrl = ApexPages.currentPage().getParameters().get('returnurl');
        String returnUrl = (ev.Id != null) 
            ? String.format('{0}/{1}', new String[] { Url.getSalesforceBaseUrl().toExternalForm(), ev.Id }) 
            : ((explicitReturnUrl != null) ? explicitReturnUrl : Url.getSalesforceBaseUrl().toExternalForm());
                PageReference page = new PageReference(returnUrl);
        page.setRedirect(true); 
        return page;                      
    }
    catch (Exception exc) {
        ApexPages.addMessages(exc);              
    }                           
    return null;
}

here the date parse code that I use:

//Parsing the Date Time for the current Time    
public Datetime parse(String startDate, String startHour) {
    List<String> hourComponents = startHour.split(':');
    return Datetime.newInstance(
        Date.parse(startDate),
        Time.newInstance(
            Integer.valueOf(hourComponents[0]),
            Integer.valueOf(hourComponents[1]),
            0, 0
        )
    );        
}

And here the functions to update user location

public PageReference ChangeTimeZone() {             
    Event ev = (Event)stdcontroller.getRecord();
    if (ev.Activity_Location__c == 'London') {
        User us = CurrentUser;
        us.TimeZoneSidKey = 'Europe/London';
        update us;
    }                         
    return null;        
}

public PageReference ChangeTimeZoneBack() {
    User usupdate = CurrentUser;  
    usupdate.TimeZoneSidKey = string.valueOf(UserTimeZone);
    update usupdate;
    return null;
}

Best Answer

Try doing -

  1. Create a custom setting for your countries list & Salesforce timezone id's i.e.(London -> Europe/London)
  2. Using the Timezone Id above get the timezone something like - TimeZone tz = TimeZone.getTimeZone('Europe/London');
  3. Create a Date/Time instance of the date & time selected DateTime dtpost = DateTime.newInstanceGMT(2012, 11, 1, 0, 0, 0);
  4. Based on the output from step 2 & 3 get the offset between the Date/Time field & the timezone - tz.getOffset(dtpost)
  5. Convert the offset received in Step 4 (in milliseconds) to hours.
  6. Add the hours from Step 5 to your Date/Time field in Step 3 using the time class addHours(additionalHours) method.
Related Topic