[SalesForce] 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.

Best Answer

Just use format() without any parameters. Note from the documentation on Datetime:

format()
Converts the date to the local time zone and returns the converted date as a formatted string using the locale of the context user. If the time zone cannot be determined, GMT is used.

Signature
public String format()

Return Value
Type: String

Example

DateTime myDateTime = DateTime.newInstance(1993, 6, 6, 3, 3, 3);
system.assertEquals('6/6/1993 3:03 AM', mydatetime.format());