Saturday, 12 January 2013

TimeZone Methods of Spring 13(API 27.0 ) release of salesforce


The timezone handling in apex was not so elegant and as a developer we had difficult times converting the GMT time zone to the locale time zone in apex language
The below code snippet demonstrates the earlier technique i had to use to convert the GMT time into the local time of the user
String timeZone = [select timeZoneSidKey from User where id=:userinfo.getUserId()].timeZoneSidKey;
System.debug('TIME ZONE '+timeZone);
Datetime dateGMT=Datetime.newInstanceGmt(2013,01,12,01,12,0);//Form the GMT time and date in sfdc
String formatteddate=dateGMT.format('yyyy-MM-dd HH:mm:ss',timeZone);//format the GMT into the Local according to his TimeZone Key
System.debug('LOCAL  TIME ....'+Datetime.valueOfGmt(formatteddate));

Debug Log
02:55:43.119 (119313000)|USER_DEBUG|[2]|DEBUG|TIME ZONE America/Los_Angeles
02:55:43.119 (119662000)|VARIABLE_ASSIGNMENT|[3]|dateGMT|"2013-01-12T01:12:00.000Z"
02:55:43.120 (120138000)|USER_DEBUG|[5]|DEBUG|LOCAL  TIME ....2013-01-11 17:12:00

debug Log analysis
  Number of SOQL queries: 1 out of 100
  Number of query rows: 1 out of 50000
Thanks to the spring 13 apex feature .No more i need query to find the TimeZoneSidKey Here is how i will structure my new code with the help of new time Zone methods
String timeZone = UserInfo.getTimeZone().getID();
System.debug('TIME ZONE'+timeZone);
Datetime dateGMT=Datetime.newInstanceGmt(2013,01,12,01,12,0);//Form the GMT time and date in sfdc
String formatteddate=dateGMT.format('yyyy-MM-dd HH:mm:ss',timeZone);//format the GMT into the Local according to his TimeZone Key
System.debug('LOCAL  TIME ....'+Datetime.valueOfGmt(formatteddate));

Debug Log
02:55:43.119 (119313000)|USER_DEBUG|[2]|DEBUG|TIME ZONE America/Los_Angeles
02:55:43.119 (119662000)|VARIABLE_ASSIGNMENT|[3]|dateGMT|"2013-01-12T01:12:00.000Z"
02:55:43.120 (120138000)|USER_DEBUG|[5]|DEBUG|LOCAL  TIME ....2013-01-11 17:12:00
debug Log analysis
Number of SOQL queries: 0 out of 100
Number of query rows: 0 out of 50000

So we have saved a query and also a query row using the native userinfo.getTimezone() Method .

 Whats more interesting is Timezone system class in apex now is capable of providing accurate offset from GMT .(I may not need to maintain any custom setting to know the offset depending on timezone of the user)

 The key points to note are as follows:

   1)The negative or positive sign is indicated while returning the integer on   userinfo.gettimezone.getOffset(DateTime);
 2)The integer is in milliseconds .


References: 

 1)http://developer.force.com/releases/release/Spring13
 2)Realease Notes Spring 13 Pdf

Introducing Lightning Base Components

Lightning Base Components are great addition to the platform and in fact revolutionary .One of the concerns around lightning component ...