tags:

views:

111

answers:

3

Hi all

I have 2 strings which are actually dates but they are in different format:

  1. 2004-06-01 00:00:00 (This value I get from Excel database through JDBC)
  2. 6/1/2004

Is their any pre-defined Class in Java which I can use to create Date kind of object? So that I can just invoke its constructor over these Strings and finally compare them.

Or will I have to write my own function to compare using String functions? Please Help.

Thanks for reading.

+4  A: 

You are looking for SimpleDateFormat.

SimpleDateFormat is an implementation of the abstract DateFormat. You first define the pattern of the date in the constructor and then use parse method.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
Date date = sdf.parse(dateString);

If you are using a Locale other than the default, you need to define it at the constructor.

kgiannakakis
+2  A: 

There is no Date constructor that accepts an arbitrarily formatted string, but you could write a method easily enough:

Date parseDate(String dateFormat, String dateValue) throws ParseException {
    return new SimpleDateFormat(dateFormat).parse(dateValue);
}

Usage:

Date myExcelDate = parseDate("yyyy-MM-dd HH:mm:ss", "2004-06-01 00:00:00");
Date myOtherDate = parseDate("d/M/yyyy", "6/1/2004");

You'll need to catch a potential ParseException. See SimpleDateFormat for format string details.

harto
+2  A: 

If you get a "Date String" from JDBC, you're doing something wrong - use ResultSet.getDate().

Michael Borgwardt