Sercan Tuğçe
Sercan Tuğçe

Reputation: 1

Convert String to Date Issue (Date Parsing) in JAVA

I am trying to convert a String like "05/30/2012" to a Date as same like "05/30/2012" and I'm using these codes.

DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

Date d1=formatter.parse("05/30/2012");

System.out.println(d1);

But these codes compile result is : "Wed May 30 00:00:00 EEST 2012" I need "05/30/2012".

Note: I'm trying to convert String to Date. I have a Date column in Database. I don't want to change it's format. I just want 05/30/2012 in my database but as a Date class not a String. parse() method is changing my date to another format I want to keep it's format

I've solved it.

java.sql.Date dd = new java.sql.Date(formatter.parse("05/30/2012").getTime());
System.out.println(dd);

and now its result is : 05/30/2012

Upvotes: 0

Views: 727

Answers (6)

Jeff Miller
Jeff Miller

Reputation: 1444

Try this:

System.out.println(formatter.format(d1));

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240966

You need to use format() method then

By the way what is the point of conversion here if you already have string formatted?

if you just say System.out.println(dateinstance); then it will invoke toString() method of Date class which has fixed format,

So if you just want the conversion from String to Date then you can do it using parse() method,

If you want formatted conversion from Date to String then you need to use format() method

Upvotes: 3

Erich Kitzmueller
Erich Kitzmueller

Reputation: 36987

There is nothing wrong with your code. The date is parsed, and in the System.out.println() call, the default implementation of Date.toString() is used. Note: the date doesn't know the format used for parsing

To "fix" it, i.e. do what you want, write

System.out.println(formatter.format(d1));

instead.

Upvotes: 0

StepTNT
StepTNT

Reputation: 3967

DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date d1=formatter.parse("05/30/2012");
String out = formatter.format(date);
System.out.println(out);

The parse method will build a Date from a String with the given pattern, but your System.out.println(d1); will just call a Date.toString().

To print the Date with a custom format, you should use SimpleDateFormatter.format that will return the String as you want

Upvotes: 1

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Just as you need to specify the format when parsing the date, you also need to specify the format when printing it, otherwise you get the default format that you are seeing.

Try:

System.out.println(formatter.format(d1))

Upvotes: 1

kukudas
kukudas

Reputation: 4934

try: System.out.println(formatter.format(d1));

Upvotes: 2

Related Questions