Find your content:

Search form

You are here

CreatedDate in user's local timezone

 
Share

I am trying to convert salesforce standard field CreatedDate to logged-in user's timezone. I am using following code

Datetime dt = Datetime.newInstance(a.CreatedDate.dateGmt(),a.CreatedDate.timeGmt());

But this is not giving right result. for e.g. I have created a record at 11/12/2012 12:50 PM (in GMT+5:30). Now when another user (in GMT-5:00) logs into the system and run the above code in developer console then he should see 11/12/2012 2:20 AM but he sees 11/12/2012 5:50 AM.

What I am doing wrong? Any Thoughts?


Attribution to: doga

Possible Suggestion/Solution #1

For the method you're using, the documentation says the returned date is in the GMT Timezone.

This should do it

Datetime GMTDate = Datetime.newInstanceGmt(2011,6,1,12,1,5);
String strConvertedDate = GMTDate.format('MM/dd/yyyy HH:mm:ss', 'America/New_York');
// Date is converted to the new time zone and is adjusted for daylight saving time. 

System.assertEquals('06/01/2011 08:01:05', strConvertedDate);

You can get the User's Timezinesidkey via a query to use dynamically per user

[select timezonesidkey from user]

Attribution to: techtrekker
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4279

My Block Status

My Block Content