tags:

views:

282

answers:

7

How can I convert a String object to a Date object?

I think I need to do something like this:

Date d=(some conversion ) "String "

Any help would be greatly appreciated.

+12  A: 

Hi, try the following:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = dateFormat.parse("1.1.2001");

For details refer to: SimpleDateFormat documentation

KB22
I think you're missing a 'y' or two.
Dave
yyou were right, thx for the note.
KB22
+1  A: 

you should parse the string with the SimpleDateFormat class

Zappi
+4  A: 

See Sun's Java tutorial and the class SimpleDateFormat

Mark
+3  A: 

Use a SimpleDateFormat with a format string, which matches your actual format:

    SimpleDateFormat sdf = 
  new SimpleDateFormat("yyyy-MM-dd");
 Date d = sdf.parse("2009-10-09");
jarnbjo
A: 

use

Date date = DateFormat.getInstance.parse( dateString );
catwalk
That gives you no control at all over what the format of the string should look like, so this is unlikely to be useful. Better use `SimpleDateFormat`, which allows you to specify the format to expect.
Jesper
+3  A: 

java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.

 DateFormat MYDate = new SimpleDateFormat("dd/MM/yyyy"); 
 Date today = MYDate.parse("09/10/2009");
TStamper
+5  A: 

Date-to-String conversion is a relatively complex parsing operation, not something you can do with a simple cast as you are trying.

You'll have to use a DateFormat. It can be as simple as:

Date d = DateFormat.getDateInstance().parse("09/10/2009");

But this changes the expected date format depending on the locale settings of the machine it's running on. If you have a specific date format, you can use SimpleDateFormat:

Date d = new SimpleDateFormat("d MMM yyyy HH:mm").parse("4 Jul 2001 12:08");

Note that the parse method will always expect one specific format, and will not try to guess what could be meant if it receives a different format.

Michael Borgwardt