General Date Parsing Method in Java

What is the best way to parse dates in Java? Is there a built-in way to parse strings such as July 18, 2011, July 18, 2011, July 18, 2011, 2011-07-18 without knowing the format in advance?

+5
source share
7 answers

There is nothing of the sort in the standard API library. Natty is a library that tries to do this, but you should know that it can only ever be “dealing with better efforts,” for example, 2/1/2012 is simply ambiguous: without meta-information about the format, it’s impossible to decide whether it is February 1 or January 2.

+8

. BalusC DateUtil, "" .

+2

DateFormat Format DateFormat.MEDIUM 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 + "\"");
    }

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

, , Parsing Trys. :

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

df1.parse(..)
df2.parse(..)

..

+2

Simpledateformat, dateformatter / , .

: ,

06.07.2011

6 7 ?

: " "

+1

. "10-12-2011". 10 12 ? , . , "", - / .

0

DateFormat.parse(...) dateformat, . : (): 18/07/2011 07/18/2011 - , , dd/mm/yyyy mm/dd/yyyy (, )?

0

, , - , 02-01-2012 ?

, , , ...

0

All Articles