0

I have a String in java. I want to convert it into Date. I have used SimpleDateFormat. But the problem is that if I pass dd-mm-yy instead of dd-mm-yyyy, then also it parses the String and converts into Date. Below is the code

 private static  SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY HH:mm:ss");
    public static void main(String args[]){
        Date d = null;
        String dat="14-01-16 21:59:59";
        try {
            d = dateFormat.parse(dat);
        }
        catch (ParseException e){
            e.printStackTrace();
        }
        System.out.println(d.toString());
    }

Ideally it show throw exception becuase in the dateFormatter I have given the format as dd-MM-YYYY but in the string I have passed dd-MM-YY format. So is there a way around to allow those Strings only which have only dd-MM-YYYY format only and disallowing the strings which have dd-MM-YY format.

user3213851
  • 1,068
  • 2
  • 12
  • 24
  • 2
    RIF (reading is fundamental). Read the SimpleDateFormat API page. note this: "For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D." – DwB Oct 27 '14 at 12:53
  • Unless you are dealing with very early dates you may reject anything that is before 1-1-1000 after reading it. – Henry Oct 27 '14 at 12:57
  • 1
    I suggest a variation of Henry's suggestion: reject everything berore 1-1-1900 (or some reasonable start date). – DwB Oct 27 '14 at 12:58

1 Answers1

3

If you don't want to accept YY, only YYYY, use a regex:

private static  SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY HH:mm:ss");
public static void main(String args[])
{
    Date d = null;
    String dat="14-01-16 21:59:59";
    try 
    {
        if(!dat.matches("\\d\\d-\\d\\d-\\d\\d\\d\\d.*"))
            throw new ParseException(dat, 7);

        d = dateFormat.parse(dat);
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }
}
Martin
  • 1,130
  • 10
  • 14