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?

1 Answer 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]
  • I tried Datetime dt = Datetime.newInstanceGMT(a.CreatedDate.dateGmt(),a.CreatedDate.timeGmt()); But this is also not working.
    – doga
    Nov 12, 2012 at 8:18
  • And you invoked format on it as above? With the appropriate Timezone string? Nov 12, 2012 at 8:22
  • No, actually my users can be in different timezones and formatting I want according to locale. Actually this final date I want to render using JavaScript. I want to make it general.
    – doga
    Nov 12, 2012 at 8:28
  • You can use select timezonesidkey from user where id=:UserInfo.getUserId() Nov 12, 2012 at 8:50
  • Since I am using Javascript to render to datetime field. So I want to just pass datetime field in current logged-in user's timezone. Fomrat method will return string and that will not of any use.
    – doga
    Nov 12, 2012 at 9:04

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.