[SalesForce] Convert String to Date in Apex and calculate the days difference

I have two String dates in apex and I want to calculate the difference in days in salesforce. I was trying with the below code, but it was giving me

Line: 4, Column: 1
System.TypeException: Invalid date: 2017-07-25 00:00:00

Here is the code for reference:

String strDate1  = '2017-07-25 00:00:00';
String strDate2 = '2017-07-21 00:00:00';

Date dt1 = Date.parse(strDate1);
Date dt2 = Date.parse(strDate2);

Integer noOfDays = dt2.daysBetween(dt1);
System.debug('No. Of Days : '+noOfDays);

Best Answer

Date.parse depends on the user's locale. In other words, for a person in the US, the string would be something like "7/21/2017", while in other places, you'd have to use a date like "21.7.2017". The exact format needed depends on the executing user's locale, and is primarily intended for use parsing dates collected from a user through the UI. Date.valueOf, on the other hand, always uses the format "yyyy-MM-dd HH:mm:ss". You'll want to read more in the Date class documentation.