10

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.

Suresh
  • 38,717
  • 16
  • 62
  • 66

8 Answers8

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

For details refer to: SimpleDateFormat documentation

Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43
KB22
  • 6,899
  • 9
  • 43
  • 52
9

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
  • 342,105
  • 78
  • 482
  • 720
4

See Sun's Java tutorial and the class SimpleDateFormat

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
3

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
  • 33,923
  • 7
  • 70
  • 94
3

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
  • 30,098
  • 10
  • 66
  • 73
1

you should parse the string with the SimpleDateFormat class

Zappi
  • 451
  • 3
  • 8
0

use

Date date = DateFormat.getInstance.parse( dateString );
catwalk
  • 6,340
  • 25
  • 16
  • 1
    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 Oct 09 '09 at 13:04
0

You can convert String object into Date object using this method. and this Java code is tested and running component in my environment.

public static Date parseStringAsDate(String dateStr, String format) throws ParseException
{
    if(null==dateStr || "".equals(dateStr))
        throw new IllegalArgumentException("dateStr must not be null or empty");
    DateFormat df = new SimpleDateFormat(format);
    return df.parse(dateStr);
}

dateStr = "17/05/2017"

format= "dd/MM/yyyy"

Yasir Shabbir Choudhary
  • 2,458
  • 2
  • 27
  • 31