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);
```

(1 votes, average: 5.00 out of 5)

Convert Datetime to (MM/dd/yyyy) Date Format in Apex

```Datetime dt = (Datetime)Account.Start_Date__c;
Date d = dt.format('MM/dd/yyyy');
```

(12 votes, average: 4.50 out of 5)

Get Month Last Date In Apex

Sample Code:

```Date dt = System.today();
Integer numberOfDays = Date.daysInMonth(dt.year(), dt.month());
Date lastDayOfMonth = Date.newInstance(dt.year(), dt.month(), numberOfDays);
System.debug('lastDayOfMonth-' + lastDayOfMonth);
```

(2 votes, average: 5.00 out of 5)

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);
```

(2 votes, average: 5.00 out of 5)
```Date dt = System.today(); //current date