Sunday, 10 December 2017

How to format Date and Date time in Apex class ?

Hi All,

We might need to display date in some other format as per requirement. For example there might be an requirement to display created date as MONTH/DAY or time as 11: 00 PM or 9 :00 AM.  

How will we do it ? 

For Time format
System.debug(Datetime.now().format('hh:mm a'));


For Date format 

 System.debug('Today--'+Date.Today());
 String daysMonth = String.valueOf(Date.Today().month()) + '/' + String.valueof(Date.Today().day());
 System.debug('daysMonth --'+daysMonth );

22:54:03.3 (3392679)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
22:54:03.3 (3811485)|SYSTEM_METHOD_ENTRY|[1]|com.salesforce.api.interop.apex.bcl.DateMethods.today()
22:54:03.3 (3885055)|SYSTEM_METHOD_EXIT|[1]|com.salesforce.api.interop.apex.bcl.DateMethods.today()
22:54:03.3 (3920613)|SYSTEM_METHOD_ENTRY|[1]|String.valueOf(Object)
22:54:03.3 (3939253)|SYSTEM_METHOD_EXIT|[1]|String.valueOf(Object)
22:54:03.3 (4125004)|SYSTEM_METHOD_ENTRY|[1]|System.debug(ANY)
22:54:03.3 (4135074)|USER_DEBUG|[1]|DEBUG|Today--2017-12-10 00:00:00
22:54:03.3 (4141876)|SYSTEM_METHOD_EXIT|[1]|System.debug(ANY)

22:54:03.3 (4268948)|SYSTEM_METHOD_ENTRY|[3]|System.debug(ANY)
22:54:03.3 (4279474)|USER_DEBUG|[3]|DEBUG|daysMonth --12/10

For more info please refer below link 

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_datetime.htm

No comments: