[SalesForce] How to get the correct current local time

I need to get the current time but to be in type DateTime.

I use:

DateTime now = System.now();

but it returns wrong time.

I execute the code in 2017-08-04 00:38:46 AM

but it returns

00:38:46:023 USER_DEBUG [138]|DEBUG|now 2017-08-03 21:38:46

How can I get my correct current local time 2017-08-04 00:38:46?

I had even tried with:

DateTime now = DateTime.parse(System.Now().format());

but I still get wrong time.

01:10:09:021 USER_DEBUG [139]|DEBUG|now 2017-08-03 22:10:00

How can I get the correct current local time?

Best Answer

This code will get you the local time for the logged in user, by leveraging the timezone offset to subtract/add from GMT. It's even smart enough to account for Daylight Saving.

TimeZone tz = UserInfo.getTimeZone();
DateTime dt = Datetime.now();

system.debug('Actual Time as String ' + dt.format());
system.debug('Offset ' + tz.getOffset(dt)/1000);
system.debug('Formatted Time ' + dt.addSeconds((tz.getOffset(dt)/1000)));

If you want to always convert to a specific timezone (e.g.: EST) then substitute the first line for:

Timezone tz = Timezone.getTimeZone('America/New_York');

Related Topic