Meaningless Drivel is fun!
The moose likes Java in General and the fly likes Convert String to Date format Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Convert String to Date format" Watch "Convert String to Date format" New topic

Convert String to Date format

Mahi Ranga
Ranch Hand

Joined: Jan 27, 2011
Posts: 35
Hi All,

I am facing one problem.that is convert String to Date Format.

my Programme is:

String dateString = "2011/03/28";

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date convertedDate = dateFormat.parse(dateString);

System.out.println(" " + convertedDate);

output of this example is:Mon Mar 28 00:00:00 GMT+05:30 2011
but i want yyyy/MM/dd output.

Please help me.

Mahi Ranga.
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3152

The best place to start is to read the JavaDatesFaq

Mohamed Sanaulla | My Blog
Claudiu Chelemen
Ranch Hand

Joined: Mar 25, 2011
Posts: 74

Why don't you print your initial dateString variable?

Otherwise, you could use the same SimpleDateFormat object to format the output:

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15084

One important thing to understand is that Date objects by themselves do not have any format. So, if you parse a string into a Date object, using for example a SimpleDateFormat object with a certain format, then the resulting Date object will not somehow remember the format that the original string had.

If you print the content of a Date object, by simply printing it out like this:

then the date will be printed using some default format that looks like "Mon Mar 28 00:00:00 GMT+05:30 2011" (what you're seeing).

To print a date with a certain format, you'd have to convert it back to a string again. You can do that by calling the format() method of your SimpleDateFormat object. However, it doesn't make much sense to first parse the string into a Date object, and then doing exactly the reverse immediately. You could just as well just print the string directly and save the work of parsing and formatting it.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Chris Beckey
Ranch Hand

Joined: Jun 09, 2006
Posts: 116

Just to add to what Jesper has stated,
A java.util.Date is really just a long value (milliseconds since 01Jan1970 GMT, if memory serves correct), and does not carry any concept of calendar date in the way we usually think of a date. The string representations that you are seeing are produced by the default Locale and its associated Calendar and DateFormat instances. If you want some specific formatting, create a SimpleDateFormat and use its format() method or get the Locale's date formats and use those.
I agree. Here's the link:
subject: Convert String to Date format
It's not a secret anymore!