0

I am trying to get the hour and date of the user's local timezone by using the below code.

now = Datetime.now();
offset = UserInfo.getTimezone().getOffset(now);
local = now.addSeconds(offset/1000);
hourNow = local.hour();
todayDate = local.date();

For example, my timezone is IST, and hence the third line of the code, that is the DateTime variable local has the following value 2021-07-05 21:00:20

But when I try to get the hour and date values from the variable local using the hour() and date() function on the 4th and 5th lines I am receiving the wrong values.

For hour() that is variable hourNow I am receiving 2 instead of 21, and for date() that is variable todayDate I am receiving 2021-07-06 00:00:00 instead of 2021-07-05 00:00:00

Can anyone please let me know what am I doing wrong here, and why am I receiving these wrong values?

3

.hour() and .date() functions show time in user local time zone already, so you do not need to add offset to now variable.

now = Datetime.now();
hourNow = now.hour();
todayDate = now.date();
1
  • That worked, I wasn't aware of this! thank you! Jul 5 at 16:02

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.