I need to parse a string that I got from a json to date while the value of the string is in the next format: yyyymmdd -

for example 20190429.

Is there another simple way to do it instead doing manipulation to convert it to other formats?

Date.parse and Date.valueOf not working here.


No, that is not an ISO date format nor any locale that I'm aware of, which means you'd need to write your own code to split out the year, month, and day components and call Date.newInstance().

Apex does not provide functionality to parse arbitrary date or date-time formats. Fortunately, this one is easy to handle with functions like String.left() and .mid(), or with a simple regular expression.

| improve this answer | |
  • Ok, Thanks a lot – Salvation Apr 29 '19 at 14:54
  • 3
    Here's your regex: String strDate = '20190512'; Pattern p = pattern.compile('(\\d{4})(\\d{2})(\\d{2})'); Matcher m = p.matcher(strDate); m.find(); Integer year = Integer.valueOf(m.group(1)), month = Integer.valueOf(m.group(2)), day = Integer.valueOf(m.group(3)); Date d = Date.newInstance(year, month, day); – sfdcfox Apr 29 '19 at 14:55
  • Hi again :) Just a small question related to it : If my string is YYMMDD and not YYYYMMDD - how can I parse it then? for example : 190512... Thank you. @sfdcfox – Salvation May 5 '19 at 6:47
  • 1
    @Salvation Change the regex to (\\d{2})(\\d{2})(\\d{2}). – sfdcfox May 5 '19 at 13:00

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.