0

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

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

2
  • 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. – David Cheng May 5 '19 at 17:25
  • He can take the current year and then instead of 20, can take current year – Sweety Kumari May 5 '19 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.