1

I have a datetime field that is populated by the user in pst timezone.I want to convert this field to the local timezone of the lead owner.How can i achieve this?I have tried this so far i am getting Invalid time error what i am missing here.Any help would be appreciated?

User currentUser = [Select TimeZoneSidKey from User where id =: lead.ownerId and isActive=true limit 1];
DateTime startDate;

system.debug('currentUser.TimeZoneSidKey'+currentUser.TimeZoneSidKey);

if(currentUser.TimeZoneSidKey!='America/Los_Angeles') {
    //TimeZone tz = TimeZone.getTimeZone(currentUser.TimeZoneSidKey);    
    string currentDate =ld.Activation_Reactivation_Date__c.format('MM/dd/yyyy HH:mm:ss', currentUser.TimeZoneSidKey);
    startDate = Datetime.valueof(currentDate);
} else {
    startDate =lead.Activation_Reactivation_Date__c;
}
1

1 Answer 1

2

I'm not sure exactly why you want to do this.

Timestamps in salesforce are stored in UTC, and then rendered to the timezone of the user that is viewing the record.

So, if you save one date time, when the lead owner views it, it will be rendered in his own timestamp.

If you stil want to convert timestamps, read on:

Unfortunately, there seems to be no way to convert time from one timezone to another. What you can do is find the timestamp that represents the point in time where the time in one user's timezone matches the current time in the other user's timezone.

This is the code I've used in the past:

private static DateTime convertBetweenTimezones (DateTime timestamp, Id originUserId, Id destUserId)
{
    TimeZone originTimezone = getUserTimezone (originUserId);
    TimeZone destTimezone = getUserTimezone (destUserId);
    Integer offsetMillis = destTimezone.getOffset (timestamp) - originTimezone.getOffset (timestamp);
    return timestamp.AddSeconds (offsetMillis / 1000);
}

private static TimeZone getUserTimezone (Id userId)
{
    User u = [SELECT TimeZoneSidKey FROM User WHERE Id =:userId];
    return Timezone.GetTimezone (u.TimeZoneSidKey);
}

Hope it helps!

1
  • Very Helpful.I am doing as the integration user populates this field which is in PST. Apr 28, 2016 at 15:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .