I got a String in hand in this format: yyyymmdd, for example: 19821117 or 19540227. I would like to turn it into a readable date in this format: dd.mm.yyyy. So 19821117 for example would be converted to: 17.11.1982. I don't need the result to be a valid Date object, a String is also fine. Any ideas...?
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35237
7
posted
0
That's what the java.text.SimpleDateFormat class does. Its parse method converts a String (in a given format) to a Date, while format converts a Date to a String.
A SimpleDateFormat works both to convert a String to a Date (via the parse() method) and a Date to a String (via the format() method).
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
0
The parse and format technique is good OO stuff. Try it and see how it works. But simple string manipulation may be 100x as fast. Look at String.substring() to see how to get the parts out.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Andrew Carney
Ranch Hand
Joined: Oct 17, 2006
Posts: 96
posted
0
Guys,
Thanks for the tip, I am familiar with SimpleDateFormat. The problem is that when I create one: SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy"); And than format my String I get: "Cannot format given Object as a Date" So, can someone please show me a working code example?
Thanks, Roy [ August 08, 2007: Message edited by: Roy Cohen ]
If you know that the format of the input string is always "yyyyMMdd" then you can also do this with some simple substring(...) calls - no need to parse it into a Date object and format it back.
As Stan already mentions above, this might work much faster than parsing it into a Date object and formatting it back into a String.
[ August 08, 2007: Message edited by: Jesper Young ]