wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Getting a Date from a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Getting a Date from a String" Watch "Getting a Date from a String" New topic
Author

Getting a Date from a String

Will Carpenter
Greenhorn

Joined: Mar 17, 2004
Posts: 26
This place is great!
Is there a method that I can pass the String "100404" or "10/04/04", (UK Style dates) and get back "Saturday, April 10, 2004" (US Style date)
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
Use the java.text.DateFormat class...you'll probably want to use the SimpleDateFormat subclass:

sev
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Note that you may find taking a look at the API documentation for the SimpleDateFormat (and perhaps the DateFormat) and the Date classes that sever oon mentioned to be useful - especially for details on the date patterns available.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Will Carpenter
Greenhorn

Joined: Mar 17, 2004
Posts: 26
Great sev and Dirk, that was very helpful!
Just one more thing:
The following code produces this output: Sat Apr 10 00:00:00 EDT 2004
Any idea how I could get rid of the "00:00:00 EDT"?

[ April 10, 2004: Message edited by: Dirk Schreckmann ]
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1871
Hi Will,
You need to use two SimpleDateFormat objects. One to parse the input to make sure the date is in the correct format and the second one to print the date in the format you want.
First format you already got working. Second format should be,
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMMMMMMMM dd yyyy");
System.out.println(sdf.format(now));
Regards
Maulin
Will Carpenter
Greenhorn

Joined: Mar 17, 2004
Posts: 26
Awesome! thanks folks!
For those who had trouble following:
Here's the output: Sat Apr 10 2004
Given this code:
String eDate = "04 10 04";
try
{
Date fDate;
fDate = new SimpleDateFormat("MM dd yy").parse(eDate);
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("EEE MMMMMMMMM dd yyyy");
System.out.println(sdf.format(fDate));
}
catch(ParseException pex)
{ System.out.println(pex);
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Getting a Date from a String