This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
I would like to write a function that accepts two parameters, one is the date format (4 possible combinations: mm-dd-yyyy, mm/dd/yyyy, dd-mm-yyyy, dd/mm/yyyy), and the other is the date according to the format in the first parameter. For example I can pass in mm/dd/yyyy and 11/13/2006. This method should always return the format in dd-mm-yyy. Can anyone give me some hint? I know I need to use SimpleDateFormat, but I am not sure which method I should use? It should look something like this:
public String formatDate(String pattern, String actualDate) {
For generating the desired output, you need a second SimpleDateFormat object that uses the pattern dd-mm-yyy. That's the one whose format method you'd call.
Originally posted by Ulf Dittmer: For generating the desired output, you need a second SimpleDateFormat object that uses the pattern dd-mm-yyy. That's the one whose format method you'd call.
I tried the following but it gives me an exception at "sdf2.format(myDate)"
public String formatDate(String pattern, String actualDate) {
Be careful though - in SimpleDateFormat, m means minutes, and M means months. Check the API for further details. If you're accepting the format string as an input, do you know that the caller will use the correct format? If there are four possibilities, it may be safer to create all 4 possible SimpleDateFormat objects at startup, then let the caller choose a format by passing an enum or int value, rather than a String. E.g. 1 means format 1, 2 for format 2, etc. An enum is usually preferable, unless you can't use JDK 5.
"I'm not back." - Bill Harding, Twister
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
I wrote the last post without seen your followup. Try replacing mm with MM, and if the problem persists, tell us what the exception said, and which line it was thrown from. It might also be useful to know what the input values of pattern and actualDate were.
Steven Marco
Greenhorn
Joined: Jul 23, 2002
Posts: 21
posted
0
Originally posted by Jim Yingst: I wrote the last post without seen your followup. Try replacing mm with MM, and if the problem persists, tell us what the exception said, and which line it was thrown from. It might also be useful to know what the input values of pattern and actualDate were.
Assuming the user passes in pattern as "MM-dd-YYYY" and userDate as "11/01/2006", the code below will output "Thur Nov 01 16:18:30 EDT 2006" for systemDate but throws an exception for finalDate and I can't see the output.
public String formatDate(String pattern, String userDate) {
Well, that's a creative way for it to interpret a month of 16. Surprising. You can use setLentient(false) to force the SDF to be more picky and throw an exception here, which seems more appropriate.