0

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.

2
  • So in a nutshell, you have to show the User's current time in his/her timezone? Dec 29, 2016 at 14:22
  • Can you post the solution for this issue? It will be great helpful
    – SFDC
    Sep 7, 2018 at 4:52

1 Answer 1

1

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());
1
  • DateTime.format() will only format the given datetime as per user local timezone but it won't convert the datetime from one timezone to another timezone. If user sitting in US and asset current time is from india then it should convert the asset datetime to US datetime(with 13:30 hrs of difference). Dec 30, 2016 at 6:11

You must log in to answer this question.

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