biezhi
biezhi

Reputation: 33

How to convert a string to a Date?

I don't know what format string is

May be 2015-10-10 or 2015/10/10, may also be 2015-10-30 15:30

Regular first I want to use to judge whether a valid date or time, and then use the SimpleDateFormat parsing, what should I do better?

All formats include:

- yyyy-MM-dd
- yyyy.MM-dd
- yyyy/MM/dd
- yyyy-MM-dd HH24:mm
- yyyy.MM-dd HH24:mm
- yyyy/MM/dd HH24:mm
- yyyy-MM-dd HH24:mm:ss
- yyyy.MM-dd HH24:mm:ss
- yyyy/MM/dd HH24:mm:ss

Upvotes: 3

Views: 225

Answers (2)

Jared Rummler
Jared Rummler

Reputation: 38121

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:

compile 'com.joestelmach:natty:0.12'

Example usage:

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:

/**
 * 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;
}

Upvotes: 1

user5372077
user5372077

Reputation:

use following date formatter to convert the date to String.
String d="2015-05-12";
DateFormat formatter  = new SimpleDateFormat("yyyy-mm-dd");
Date a=formatter.parse(d);

Upvotes: 1

Related Questions