Stack Overflow archive
1 scoreaccepted

How to convert a string to a Date?

score
1
question views
234
license
CC BY-SA 3.0

I've used Natty Date Parser for this. You can try it out here. It is available on maven central here. If you are using gradle:

java
compile 'com.joestelmach:natty:0.12'

Example usage:

java
String[] exampleDates = {
    "2015-10-10",
    "2015/10/10",
    "2015-10-30 15:30"
};

Parser parser = new Parser();
for (String dateString : exampleDates) {
  List<DateGroup> dates = parser.parse(dateString);
  Date date = dates.get(0).getDates().get(0);
  System.out.println(date);
}

Output:

Sat Oct 10 20:51:10 PDT 2015

Sat Oct 10 20:51:10 PDT 2015

Fri Oct 30 15:30:00 PDT 2015


EDIT:

If you know the date formats then the following StackOverflow would be better than adding a dependency to your project:

https://stackoverflow.com/a/4024604/1048340


The following static utility method might suffice:

java
/**
 * Parses a date with the given formats. If the date could not be parsed then {@code null} is
 * returned.
 *
 * @param formats the possible date formats
 * @param dateString the date string to parse
 * @return the {@link java.util.Date} or {@code null} if the string could not be parsed.
 */
public static Date getDate(String[] formats, String dateString) {
  for (String format : formats) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    try {
      return sdf.parse(dateString);
    } catch (ParseException ignored) {
    }
  }
  return null;
}

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.