I have a code which does this,

Datetime dt = Datetime.NOW();
String   starttime = dt.hour();

Now from the apex documentation, now() returns the current datetime based on GMT and hour() returns the hour component of the datetime in the local timezone of the context user.

Given this, I know that all the apex code always runs in the system context. SO I wanted to understand what is the context user here whose timezone will be considered to return the hour value. Also, does with sharing or without sharing have any effect on the hour() value ?

In my case this code is part of a web service code and is called in the context of an integration user. But I am not getting the expected values for hour() component.

1 Answer 1


Salesforce Stores the date and DateTime format in GMT/UTC. When you call DateTime.now it returns dateTime in the format of the running user's Timezone.

  1. Its TimeZone will be of the context user who executed the batch/trigger/scheduler/every apex.
  2. Sharing /Without Sharing is only for record level access. It has nothing to do with timezone.

Check the timezone of the Integration User, All code if run in his context then his timezone will be applied.

  • that makes sense. But, that is what is not happening in my code. Access user's timezone is GMT-5 on the user record but I get hour component values with respect to GMT+5 for some reason. Also, how is the context user decided when a method of a class is a webservice and is called from some external platform using WSDl ?
    – Yogesh D
    Apr 25, 2018 at 21:12
  • 1
    It will be called using sessionID or acces_token of a user. So the context and timezone of the user whose sesssionId is given is in consideration Apr 25, 2018 at 21:31
  • and so in my case integration user is used so its context is set. but timezone on the integration user record is set to GMT-5 but I get the hour value according to GMT+5 for some reason.
    – Yogesh D
    Apr 26, 2018 at 20:15

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.