Java Dateformat — Can I compare input to certain f

2019-09-12 06:31发布

问题:

For example:

A user can enter 01/23/1983 or 1/23/1983

How would I use DateFormat to write up two different kinds of formats like (MM/DD/YYYY) and (M/DD/YYYY) and compare them to the actual date to see which one matches the date so I could parse it successfully?

回答1:

Because Johan posted an incorrect solution, I feel obliged to post the correct one. "MM/dd/yyyy" will format both of your test Strings:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatTest {
   public static void main(String[] args) {
      String[] tests = {"01/23/1983", "1/23/1983", "1/3/1983"};

      String formatString = "MM/dd/yyyy";

      SimpleDateFormat sdf = new SimpleDateFormat(formatString);

      for (String test : tests) {
         Date date = null;
         try {
            date = sdf.parse(test);
         } catch (ParseException e) {
            e.printStackTrace();
         }
         System.out.println(date);
      }
   }
}


回答2:

A common solution when dealing with multiple input formats is to try a series of expected formats in a loop until one succeeds, or all fails. E.g.,

public Date parseDate(List<DateFormat> formats, String text) {
    for(DateFormat fmt : formats) {
        try {
          return fmt.parse(inputDate);
        } catch (ParseException ex) {}
    }
    return null;
}

List<DateFormat> formats = Arrays.asList(new SimpleDateFormat("MM/dd/yyyy"));
Date d1 = parseDate(formats, "01/23/1983");
Date d2 = parseDate(formats, "1/23/1983");