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?

4
  • Why do we get so many Date/String conversion questions without searching on Google??? Search for SimpleDateFormat Commented Mar 25, 2014 at 8: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. Commented Mar 25, 2014 at 8: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. Commented Mar 25, 2014 at 8:39
  • This inherent ambiguity is why the 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. Commented Sep 19, 2017 at 1:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.