I wrote a question below : String parse to Date yyyymmdd

But now I'm facing a new similar question :

What if I want to parse a string yymmdd to a date?

for example :

190503 instead of 20190503.

When I do the following :

String dateToConvert = '190503';

Date mydate =  Date.newInstance(Integer.valueOf(dateToConvert.left(2)), Integer.valueOf(dateToConvert.mid(2,2)), Integer.valueOf(dateToConvert.right(2)));

I get 0019-05-03.

I get the date value from a webservice - and I can replace the first two zeros with '20', and it will be work for a long time, but there is another way to do it and not hardcoded?

Thanks in advance!

1 Answer 1


First, you need to convert your mydate value into a string then get first two characters from string and replace these first two characters with the value you want.

Please check below code, it will help you in achieving your requirement.

String dateToConvert = '190503';

Date mydate =  Date.newInstance(Integer.valueOf(dateToConvert.left(2)),Integer.valueOf(dateToConvert.mid(2,2)), Integer.valueOf(dateToConvert.right(2)));
String value  = string.valueOf(mydate); // converting date  into string
String firstwoChar = value.substring(0,2); // getting first two characters 
string valueReplace = value.replace(firstwoChar,'20'); 

Here is the result for above code: Debug Log

  • 1
    The OP says he already knows how to add "20", his question is how to avoid hardcoding when the year becomes 2100, 2101, etc. Commented May 5, 2019 at 17:25
  • He can take the current year and then instead of 20, can take current year Commented May 5, 2019 at 17:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .