System.now function is not working as appropriate – Salesforce Apex Issue

I am using system.now() in a controller in my application. Later I have so many calculations with it.
But Date time calculations are not as per timezone of my client. Why?

Solution: Yes. It will happens because, System.now() returns the DateTime in GMT time zone, whereas System.now().hour() and
System.now().format() are the methods of DateTime class, which return the local time zone of current logged in user.

But, one thing we have to find is that System.now() will return DateTime and all other methods of DateTime will be string. It means, System.now().format() will output as string, which is calculated with logged in user’s time zone.

Datetime.NewInstance() will create a datetime in SYSTEM’s time zone.
Datetime.NewInstanceGmt() will create a datetime in GMT time zone.

String day = string.valueOf(system.now().day());
String month = string.valueOf(system.now().month());
String hour = string.valueOf(system.now().hour());
String minute = string.valueOf(system.now().minute());
String second = string.valueOf(system.now().second());
String year = string.valueOf(system.now().year());

String strTime = year+’-‘+month+’-‘+day+’ ‘+hour+’:’+minute+’:’+second ;

system.debug(strTime);
system.debug(system.now());

Output 1: 2016-11-25 20:46:47
Output 2: 2016-11-25 15:16:47

Related posts