1

I have string in below format

0030k000002HsSaAAK#2009-06-21 00:00:00,0030k000002HpvTAAS#2003-05-08 00:00:00,0030k000002uxiyAAA#2011-06-29 00:00:00,

I have to separate out only dates from this like 2009-06-21, 2003-05-08 and 2011-06-29 and then I have to do comparison of the dates and find out the latest date. Can anyone help me in splitting this.

Here's my current code:

set<String> dateSet = new set<String>();
String s='0030k000002HsSaAAK#2009-06-21 00:00:00,0030k000002HpvTAAS#2003-05-08 00:00:00,0030k000002uxiyAAA#2011-06-29 00:00:00,';
List<String> splitstr = new List<String>();
splitstr = s.split('[,]{1}[\\s]?');
system.debug('splitstr'+splitstr[0]);
2
  • What did you try so far? Commented Sep 4, 2017 at 11:48
  • set<String> dateSet = new set<String>(); String s='0030k000002HsSaAAK#2009-06-21 00:00:00,0030k000002HpvTAAS#2003-05-08 00:00:00,0030k000002uxiyAAA#2011-06-29 00:00:00,'; List<String> splitstr = new List<String>(); splitstr = s.split('[,]{1}[\\s]?'); system.debug('splitstr'+splitstr[0]);
    – wizard
    Commented Sep 4, 2017 at 11:50

2 Answers 2

3

You can do this using regex:

Pattern p = Pattern.compile('(\\d{4}-\\d{2}-\\d{2})+');
Matcher pm = p.matcher('0030k000002HsSaAAK#2009-06-21 00:00:00,0030k000002HpvTAAS#2003-05-08 00:00:00,0030k000002uxiyAAA#2011-06-29 00:00:00,');

List<String> dates = new List<String>();
if(pm.find()) {
   do{
       dates.add(pm.group());
   }while(pm.find());
}
System.debug(dates);

OUTPUT

(2009-06-21, 2003-05-08, 2011-06-29)

2
0

If you can guarantee that the format will always be like this:

<id>#<date><space>

then you can get the string, use the split method from the String class, and then iterate the strings and get the date using the substring method, like this:

List<String> dates = new List<String>();
Set<String> data = myString.split(' ');
for (String s : data) {
    dates.add(s.substring(20, 30));
}

Note that with this example you will need to parse the date if you want to work with the Date class, but that can be easily achieved inside the for loop.

2
  • {List<String> dates = new List<String>(); String st='0030k000002HsSaAAK#2009-06-21 00:00:00,0030k000002HpvTAAS#2003-05-08 00:00:00,0030k000002uxiyAAA#2011-06-29 00:00:00,'; Set<String> data = st.split(' '); for (String s : data) { dates.add(s.substring(20, 30)); } System.debug('dates'+dates);}
    – wizard
    Commented Sep 4, 2017 at 12:12
  • getting error Illegal assignment from List<String> to Set<String> for Set<String> data = st.split(' ');
    – wizard
    Commented Sep 4, 2017 at 14:15

You must log in to answer this question.

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