Generic way to parse dates in Java

后端 未结 7 957
醉酒成梦
醉酒成梦 2021-01-19 00:03

What is the best way to parse dates in Java ? Is there any built in way to parse strings such as \"18 Jul 2011\" , \"Jul 18, 2011\", \"18-07-2011\", \"2011-07-18\" without k

7条回答
  •  感动是毒
    2021-01-19 00:40

    try DateFormat with the default Format DateFormat.MEDIUM and SHORT.

    public static void main(String[] args) {
        // Make a String that has a date in it, with MEDIUM date format
        // and SHORT time format.
        String dateString = "Nov 4, 2003 8:14 PM";
    
        // Get the default MEDIUM/SHORT DateFormat
        DateFormat format =
            DateFormat.getDateTimeInstance(
            DateFormat.MEDIUM, DateFormat.SHORT);
    
        // Parse the date
        try {
            Date date = format.parse(dateString);
            System.out.println("Original string: " + dateString);
            System.out.println("Parsed date    : " +
                 date.toString());
        }
        catch(ParseException pe) {
            System.out.println("ERROR: could not parse date in string \"" +
                dateString + "\"");
        }
    

    Snipped from http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/

    On exception you have to decide what todo next, you can build a hierarchy of Parsing Trys. like:

    SimpleDateFormat df1 = new SimpleDateFormat( "dd/MM/yyyy" );
    SimpleDateFormat df2 = new SimpleDateFormat( "dd-MM-yyyy" );
    
    df1.parse(..)
    df2.parse(..)
    

    and so on.

提交回复
热议问题