ShowAll Questionssorted byDate Posted

# How to Set the first two digits of dates to “19” or “20” depending on input of second two digits of year?

If type 15/10/95 it should change to 15/10/1995 where as 1/1/10 it should change to  1/1/2010
SKSANJAY
Hi Ajit,

Where actually you are looking for this? And another thing is that if suppose user has entered "1/1/10" as a date and he actually meant to set 1910 then what will happen?

String selectedDate = '15/10/10';
System.debug('selectedDate : ' + selectedDate);
Integer currentYear = system.today().year();
Integer shortCurrentYear = Integer.valueOf((String.valueOf(currentYear)).substring(2));
System.debug('currentYear : ' + currentYear);
System.debug('shortCurrentYear : ' + shortCurrentYear);
String formattedDate = selectedDate.substring(0, selectedDate.lastIndexOf('/'));
Integer selectedYear = Integer.valueOf(selectedDate.substring(selectedDate.lastIndexOf('/') + 1));

if(selectedYear > shortCurrentYear){
formattedDate += '/19' + selectedYear;
}else{
formattedDate += '/20' + selectedYear;
}

System.debug('formattedDate : ' + formattedDate);

But remember above code will not work if User has entered year less that current year and he was trying to set 1900 year.

SKSANJAY
Hi Ajit,

Where actually you are looking for this? And another thing is that if suppose user has entered "1/1/10" as a date and he actually meant to set 1910 then what will happen?

String selectedDate = '15/10/10';
System.debug('selectedDate : ' + selectedDate);
Integer currentYear = system.today().year();
Integer shortCurrentYear = Integer.valueOf((String.valueOf(currentYear)).substring(2));
System.debug('currentYear : ' + currentYear);
System.debug('shortCurrentYear : ' + shortCurrentYear);
String formattedDate = selectedDate.substring(0, selectedDate.lastIndexOf('/'));
Integer selectedYear = Integer.valueOf(selectedDate.substring(selectedDate.lastIndexOf('/') + 1));

if(selectedYear > shortCurrentYear){
formattedDate += '/19' + selectedYear;
}else{
formattedDate += '/20' + selectedYear;
}

System.debug('formattedDate : ' + formattedDate);

But remember above code will not work if User has entered year less that current year and he was trying to set 1900 year.
This was selected as the best answer
Hi Sanjay,

I appreciate your effort. I wanted a condition where if the year in two digit is greater than 60 then it should take 19 otherwise 20
SKSANJAY
Perfect, then just change the below code

if(selectedYear > shortCurrentYear){

to

if(selectedYear > 60){

your requirement will be done.. Just use anonymous block to execute the code after making changes.

Thanks,
Sanjay