Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Convert String to Date format

 
Mahi Ranga
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Regards
Mahi Ranga.
 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The best place to start is to read the JavaDatesFaq
 
Claudiu Chelemen
Ranch Hand
Posts: 75
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why don't you print your initial dateString variable?

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




Cheers!
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Chris Beckey
Ranch Hand
Posts: 116
Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic