+ Start a Discussion
Mohammed AzarudeenMohammed Azarudeen 

Display string DateTime in Current User Locale

I want to display the dynamic string date time to current user local date time.

My code sample : 
DateTime currentDate = System.now();
//convert to asset local date time with rawOffset and dstOffset(for this case it is Indian Timezone)
DateTime assetUTCDate = currentDate.addSeconds((integer.valueOf(rmaRawOffset) + integer.valueOf(rmaDstOffset)));
DateTime addDays = assetUTCDate.addDays(1);
//adding days and setting time and assigning to String Field in asset
assetToProcess.assetSLADueDateTime__c = string.valueOf(DateTime.newInstance(addDays.yearGmt(), addDays.monthGmt(), addDays.dayGmt(), 17, 0, 0).format('MM-dd-YYYY HH:mm:ss'));
//Get the string field datetime and convert to user locale datetime
//Consider this is '12-22-2016 17:00:00' a string datetime we got from previous step. If it Indian Standard Time, //I need to show this time to corresponding current user locale time in another asset field.
assetToProcess.SLAInUserLocaleDateTime = ////////user locale datetime from previous date time///////;

for example : 
assetToProcess.assetSLADueDateTime__c = '12-22-2016 17:00:00';
//Convert it to user locale. Say if the user is in PST which is 13.30 hours behind Indian time. So I need to show //the user locale field as
assetToProcess.SLAInUserLocaleDateTime = 12/22/2016 3:30 AM;

I have tried wit,
  1. DateTime.newInstanceGMT - but it shows 12/22/2016 9:00 AM. Which is only reducing -8:00 hours of PST GMT and not reducing from Indian GMT which is -5:30
  2. DateTime.newInstance - it shows 12/22/2016 5:00 PM. It is displaying the actual datetime with PST format
  3. DateTime.parse - gives invalid date time error.
  4. DateTime.valueOf 
So, what I need to do to display the datetime in current user locale. 
Any help is appreciable. Thanks.
sukanya banekarsukanya banekar

You can get current user timezone using query User objUser= [select timezonesidkey from user where Id =:UserInfo.getUserId()']; in your apex code.
Datetime dtDateTime= system.now();
string strDateTime= dtDateTime.format('MM/dd/yyyy HH:mm:ss', objUser.timezonesidkey );

I hope this helps you to get string DateTime in Current User Locale.

Sukanya Banekar