0

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

2 Answers 2

1

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.

0

Here I tried using valueOf(stringDate) and it works fine. Not sure why with parse(stringDate) its not working.

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

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

Integer noOfDays = dt2.daysBetween(dt1);
System.debug('No. Of Days : '+noOfDays);
1
  • 1
    If you are still looking for answers, you might get more looks if you add this detail to your question instead of posting as an answer.
    – Adrian Larson
    Jul 21, 2017 at 17:36

You must log in to answer this question.