Tag Archives: Datetime

Converting DateTime to Date in Salesforce

Solution 1: Create a date newInstance() and pass the Year, Month and Day from the dateTime.

DateTime dt = System.now();
Date d = Date.newInstance(dt.year(), dt.month(), dt.day());
System.debug('Print Date:' + d);

Solution 2: Get date from the DateTime using Date() method.

DateTime dt = System.now()
Date d = dt.date();
System.debug('Print Date:' + d);

Calculate The Difference Between Two DateTime Fields In Salesforce Apex

Sample Code:

Account acc = [Select Id, Name, CreatedDate, LastModifiedDate From Account LIMIT 1];
Long createdDateTime = acc.CreatedDate.getTime();
Long modifiedDateTime = acc.LastModifiedDate.getTime();
Decimal diffMilliSecs = Decimal.valueOf(modifiedDateTime - createdDateTime);

Decimal dDays = diffMilliSecs/1000/60/60/24;
Integer iDays = Integer.valueOf(math.floor(dDays));
Decimal remainderDays = dDays- iDays;

Decimal dHours = remainderDays * 24;
Integer iHours = Integer.valueOf(math.floor(dHours));
Decimal remainderHours = dHours - iHours;

Decimal dMinutes = remainderHours * 60;
Integer iMinutes = Integer.valueOf(math.floor(dMinutes));
Decimal remainderMinutes = dMinutes - iMinutes;

Decimal dSeconds = remainderMinutes * 60;
Integer iSeconds = Integer.valueOf(math.floor(dSeconds));
Decimal remainderSeconds = dSeconds - iSeconds;

System.debug('Days: ' + iDays+' - '+'Hours: ' + iHours+' - '+'Minutes: ' + iMinutes+' - '+'Seconds: ' + iSeconds);