function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
James BillingsJames Billings 

Insert date field keeping local timezone?

I've added a date field to an object, which is populated with a simple formula of "NOW()". 
The problem is that this inserts the date as UTC. What I actually need to happen is that the value is inserted using the date/time of the user submitting the item for approval.
For example, it's currently 7am on the 29th June here in the UK. If I log in via a computer in Pacific time where the local time is still the day before (28th) and submit approval, the date is still populated as the 29th. 
How can I get this to be filled in with the date value of the user requesting approval?
James BillingsJames Billings
Thanks, I'll try that out
Vinit JoganiVinit Jogani
Hi James,

Any specific reason why you want to store in local timezone? Salesforce stores all date time in UTC. while displaying, it converts it based on the timezone of Org and User. So if your user is in PST, it will still see the date and time of 28th and not 29th. Whereas the person in UK will see same as 29th.

Hope this clarifies.
James BillingsJames Billings
Hey Vinit,
Yes, the actual result I want would be for the UK to also see 28th - basically sales people in different offices will make a request for an approval. For the purposes of calculating their figures, we would take the date they submitted this... This would matter on the last day of the month for example; if someone in the US submits a request at the end of the day on the 31st, but Salesforce converts to UTC (so it shows 1st) their figure for that would be in the wrong month. We want it to stay as 31st, and the finance processors in the UK also need to see 31st.
Hope that makes sense.
Vinit JoganiVinit Jogani
Hi James,

That does make sense. In that case you might want to use Timezone class. Implement some logic where you are taking current time, take users timezone (UserInfo.getTimeZone()), find out offset, subtract it from current time and then store. With that, even if it is stored as UTC, it will reflect correct time.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_timezone.htm 

E.g. UTC time is 29th 4 am means PST time is 28th 8pm.
If you take current time: 29th 4 am and substract 8hrs from it, it will be 28th 8pm and this will be stored in your object field.

I hope this works.