Sunday, May 23, 2010

String Regex and Date Format

Even though these classes have been around for years, I quite often see people handle String manipulation and Date formatting is some "interesting" ways.

I was reading some log files checking dates and graphing the result with jfreechart and came up with, seems quite clean and neat.

package bob.blog;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The Class FindADateInAString.
 */
public class FindADateInAString {
 
 /** The formatter. */
 private static SimpleDateFormat formatter = (SimpleDateFormat) DateFormat
 .getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
 
 
 /**
  * The main method.
  *
  * @param args the arguments
  * @throws ParseException the parse exception
  */
 public static void main(String[] args) throws ParseException {
  List< Date > dates = returnDatesFromAString("This string contains some random dates: 2010-03-06 01:11:06 and 2009-03-10 23:11:05");
  System.out.println(dates);
 }
 
 
 /**
  * Return dates from a string.
  *
  * @param toParse the to parse
  * @return the list
  * @throws ParseException the parse exception
  */
 public static List< Date > returnDatesFromAString(final String toParse) throws ParseException{
  List< Date > dates = new ArrayList< Date >();
  String regex = "(\\d+\\-)+\\d+\\s(\\d+\\:)+\\d+";
  Pattern pattern = Pattern.compile(regex);
  Matcher matcher = pattern.matcher(toParse);

  while (matcher.find()) {
   formatter.applyPattern("yyyy-MM-dd hh:mm:ss");
   dates.add(formatter.parse(matcher.group()));
  }
  
  return dates;
 }
 
 
}


No comments:

Post a Comment

Popular Posts

Followers