0

How can this 11/03/2009-20:06:16 to a Date object so I can compare two dates. I keep getting java.lang.IllegalArgumentException: Cannot format given Object as a Date error if I use below implementation.. I need the output to be date object with format Tue Jul 14 01:32:31 2009

  import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Dateaf {

    /**
     * @param args
     * @throws ParseException
     */
    public static void main(String[] args) throws ParseException {
        // TODO Auto-generated method stub

        String text = "11/03/2009-20:06:16";

        SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy-hh:mm:ss");

        Date date = dateParser.parse(text);
        System.out.println(date);

    }

}
jrdnsingh89
  • 215
  • 2
  • 7
  • 18

3 Answers3

3

sdf.format() takes a Date object and returns a String. You are passing a String to it.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
2

You are very close, just drop the call to format:

Date date = sdf.parse(text);

So:

String text = "11-03-2009 20:06:16";

SimpleDateFormat dateParser = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
                                                             //^^ capital H for 24 hour  

Date date = dateParser.parse(text);

And to print (from your comment in the format "Tue Jul 14 01:32:31 2009"):

SimpleDateFormat dateFormatter = new SimpleDateFormat("EE MM dd HH:mm:ss yyyy");

System.out.println(dateFormatter.format(date));

The SimpleDateFormat javadoc is an excellent reference for formats.

EDIT

After OP's edits here is a full example

public static void main(String[] args) throws ParseException {
    final String text = "11/03/2009-20:06:16";
    final SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
    final Date date = dateParser.parse(text);
    final SimpleDateFormat dateFormatter = new SimpleDateFormat("EE MMM dd HH:mm:ss yyyy");
    System.out.println(dateFormatter.format(date));
}

Output:

Tue Nov 03 20:06:16 2009
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
-1

Java has the text package which gives us the predefined class text

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
public static void main(String[] args) throws Exception{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

Date today = df.parse("20/12/2005");
System.out.println("Today = " + df.format(today));
}
}

There is another way of doing this

String date = "2000-11-01";
java.sql.Date javaSqlDate = java.sql.Date.valueOf(date);
Madara
  • 150
  • 1
  • 8