1

In my code, I've to convert a String value(Input) to java.sql.Date format. The problem I am facing is , the input date format is undefined, and it could be in any format. For example , input string may be "Jan 10,2014" or "01-10-2014" or "2014/Jan/10". So now I need to convert this input value into java.sql.Date(DD/MMMM/YYYY). Is there any way to do this conversion?

Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
Gokulram
  • 83
  • 7
  • Why do we get so many Date/String conversion questions without searching on Google??? Search for `SimpleDateFormat` – sidgate Mar 25 '14 at 08:34
  • 2
    IMO You will need to specify all date formats that you would like to handle and then try to parse with each one. – Subir Kumar Sao Mar 25 '14 at 08:37
  • 3
    Out of interest, how do you know 01-10-2014 is 1st October 2014 and not 10th January 2014. If you can influence the data format on your input, now is the time to do it as, if the date format on the input is not constrained, you can't unambiguously convert it to a date. – DaveH Mar 25 '14 at 08:39
  • This inherent ambiguity is why the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) standard was devised. Use those standard formats instead if at all possible. The java.time classes use these formats by default when parsing/generating textual representations of date-time values. – Basil Bourque Sep 19 '17 at 01:25

2 Answers2

4

That is not possible.

You cannot differentiate dd/MM/yyyy and MM/dd/yyyy.

You really need to know the format otherwise your program will probably not behave the way you want.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
0

Try using a List of all the patterns mentioned above using SimpledateFormat.

Something like this:

    SimpleDateFormat format1 = new SimpleDateFormat("MMM dd,yyyy");
    SimpleDateFormat format2 = new SimpleDateFormat("MM-dd-yyyy");
    SimpleDateFormat format3 = new SimpleDateFormat("yyyy/MMM/dd");

    // Note: be sure about the format, or else you may end up assigning incorrect values
    List<DateFormat> list = new ArrayList<DateFormat>();
    list.add(format1);
    list.add(format2);
    list.add(format3);

    for (DateFormat format : list) {
        try {
            System.out.println(format.parse("Jan 10,2014"));
            // Match found. Take action
        } catch (ParseException exception) {
            // Ignore. Try other pattern
        }
    }
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38