0

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.

3

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.

  • Ok, Thanks a lot – Salvation Apr 29 at 14:54
  • 2
    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 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 at 6:47
  • 1
    @Salvation Change the regex to (\\d{2})(\\d{2})(\\d{2}). – sfdcfox May 5 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.