0

I have the following code to get the DateTime for EST Time Zone

Timezone tz = Timezone.getTimeZone('America/New_York');
DateTime now = Datetime.now();
Datetime localTime = now.addSeconds((tz.getOffset(now)/1000));
String timeString = String.valueOf(localTime);

The following debug logs return this

System.debug(localTime); // 2023-04-08 03:46:32 
System.debug(timeString); // 2023-04-07 23:46:32

The top System.debug is correct, the bottom one is wrong, i was expecting the same as the top just as a string

What am I missing?

1 Answer 1

1

Both are correct:

  • System.debug(datetime) always shows the datetime in UTC
  • String.valueOf(datetime) converts it to your local time zone and returns that string

Since your time zone is New York (I guess), so UTC-4, the difference between the two System.debug is 4 hours.

Try System.debug(String.valueOf(now)); and you'll see the same value of System.debug(localTime);

You must log in to answer this question.

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