File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Date Confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Date Confusion" Watch "Date Confusion" New topic
Author

Date Confusion

Crystal Bazil
Ranch Hand

Joined: Sep 28, 2004
Posts: 38
I am building a form that allows a user to select two dates(input boxes)in which to perform a search on. The users entered criteria will always be formatted to the MM/dd/yyyy format. However, in order for my query to work I need to format the date as follows: yyyy/MM/dd.

Otherwise I get the following exception:


I have googled, search SDN forums and here but I haven't found the solution to my problem.

I have tried the following in my servlet(from examples online):



What I dont understand is the out print lines I am logging which are as follows:



Which API should I be looking at? It seems like I need to use both java.text.SimpleDateFormat and java.text.DateFormat or perhaps one or the other. Why are my print outs so completely off my actual input dates? And is there a way to format a date string from MM/dd/yyyy to date yyyy/MM/dd?

I would appreciate any clarification on the above issues.

Thanks in advance - regards,
Crystal Bazil
[ December 09, 2005: Message edited by: Crystal Bazil ]
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4419
    
    5

Since your input is in MM/dd/yyyy format, the SimpleDateFormat object that parses that string should be created like so:

// input to parse is in MM/dd/yyyy format, not yyyy/MM/dd
SimpleDateFormat mmddyyyy = new SimpleDateFormat("MM/dd/yyyy");
Date start = mmddyyyy.parse(inputStr);

// If you want to output as yyyy/MM/dd, you need another SimpleDateFormat:
SimpleDateFormat yyyymmdd = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(yyyymmdd.format(start));
[ December 09, 2005: Message edited by: Junilu Lacar ]

Junilu - [How to Ask Questions] [How to Answer Questions]
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4419
    
    5

Or you change the pattern by passing in a new format string to the applyPattern() method of the same SDF object.

The thing to remember is that parse() uses the pattern to determine what format the input (the String you are parsing) should be in. On the other hand, format() uses the pattern to determine the format of the output.
Crystal Bazil
Ranch Hand

Joined: Sep 28, 2004
Posts: 38
Junilu - Your solution solved my issue. I appreciate the explanation and you time!

Crystal
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Date Confusion
 
Similar Threads
dates
Get Dates between the given dates.
Max Date Limit
How to change Date Format
Calculating no. of working days between tow dates