Skip to main content

Posts

Showing posts with the label how to get time from datetime in apex

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(AN...

How to calculate time spent or no of days between two day time value ?

Hi All, This post explains how to  calculate time spent and no of days between two date time value and issue faced while doing same and how to resolve those. First Try  Account acc = [select id,createddate,lastmodifieddate from Account limit 1]; datetime diff = acc.lastmodifieddate - acc.createddate; System.debug('diff --'+diff ); Error -  COMPILE ERROR: Date/time expressions must use Integer or Double or Decimal LINE: 3 COLUMN: 14  Second Try  Account acc = [select id,createddate,lastmodifieddate from Account limit 1]; Integer diff = Integer.valueOf(acc.lastmodifieddate) - Integer.valueOf(acc.createddate); System.debug('diff --'+diff ); Error EXCEPTION: System.TypeException: Invalid integer: java.util.GregorianCalendar[time=1455789326000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=2,mi...