1

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.

0

1 Answer 1

4

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.

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

You must log in to answer this question.

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