[SalesForce] System.TypeException: Invalid date: 2015-06-04

If I changed the time zone in Salesforce Org then getting the 'Invalid date Error'.
It works fine if I select the Indian time zone but If I select other than current Timezone then Displaying error while parsing the date.

The Code is like this:

String dayOrDate = '2015-06-04';

List <String> dateParts = dayOrDate.split('-');

Date tempDate = date.parse(dateParts[1]+'/'+dateParts[2]+'/'+dateParts[0]);

Datetime dateWithTime = datetime.newInstance(tempDate.year(), tempDate.month(),tempDate.day());

dayOrDate = dateWithTime.format('dd- MMM-yy');

Please Can anyone please point me to solution ?
Thanks in Advance!!

Best Answer

You are using date.parse on a string that you construct as centre number / right number / left number

So in your example you turn 2015-06-04 into 04/06/2015. I would understand this as the 4th of June but our american friends would (wrongly) think that this is 6th of April.

When you call date.parse it uses the users settings to decide whether it should be mm/dd/yyyy or dd/mm/yyyy

So for some dates and users it will fail because it mixes month and day.

String dayOrDate = '2015-06-30';
List<String> dateParts = dayOrDate.split('-');
Datetime dateWithTime = Datetime.newInstance(Integer.valueOf(dateParts[0]), Integer.valueOf(dateParts[1]), Integer.valueOf(dateParts[2]));
dayOrDate = dateWithTime.format('dd- MMM-yy');
System.debug(dayOrDate);

returns

30- Jun-15

Related Topic