This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes No exception when parsing date from string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "No exception when parsing date from string" Watch "No exception when parsing date from string" New topic
Author

No exception when parsing date from string

Michael Remijan
Author
Ranch Hand

Joined: May 29, 2002
Posts: 123
    
    5

Hello,
I think I should be getting an exception here but i'm not. I have:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", user.getLocale());
When I try to parse an *invalid* date I expected an exception to be thrown:
sdf.parse("99/99/9999");
I am NOT getting an exception and Java returns a java.util.Date object with the toString value:
Thu Jun 07 00:00:00 CDT 10007
Shouldn't the parse() method have thrown an exception? How do I get it to?
Tom Blough
Ranch Hand

Joined: Jul 31, 2003
Posts: 263
Why do you think you should get an exception? According to the API the only exception thrown by parse is a NullPointerException, and your invalid date certainly was not null.


Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
toggle on/off the sdf.setLenient(false) to see what happens
Tom Blough
Ranch Hand

Joined: Jul 31, 2003
Posts: 263
parse is still not throwing an exception. With leinent off, parse is returning null, and setTime is throwing a NullPointerException.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
According to the API the only exception thrown by parse is a NullPointerException, and your invalid date certainly was not null.
That's true for parse(String, ParsePosition) - but not parse(String) which is defined in DateFormat and not overridden. Michael, could you show the code you're using to parse this?


"I'm not back." - Bill Harding, Twister
Michael Remijan
Author
Ranch Hand

Joined: May 29, 2002
Posts: 123
    
    5

Michael Dunn's tip worked for me, thanks Michael. When I set lienient to false, the parsing would not allow dates like 99/99/9999 or 4/40/2004.
If lienient is not working for you, search through your code for "new SimpleDateFormat" and ".getInstance". The first time I tried setting lienient to false did not work because I missed a place in my code where I create a DateFormat object with ".getInstance"
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: No exception when parsing date from string