import java.util.*;
import java.text.*;
class Test{
public static void main(String args[]){
SimpleDateFormat yyyymmddFormatter = new SimpleDateFormat("yyyyMMdd");
yyyymmddFormatter.setLenient( false );
Date newDate = yyyymmddFormatter.parse( "xxx" , new ParsePosition(0) );
System.out.println("date is " + newDate);
}
}
returned - date is Thu Jan 01 00:00:00 GMT+00:00 1970
we fixed with...
import java.util.*;
import java.text.*;
class Test{
public static void main(String args[]){
SimpleDateFormat yyyymmddFormatter = new SimpleDateFormat("yyyyMMdd");
yyyymmddFormatter.setLenient( false );
Date newDate = yyyymmddFormatter.parse( "xxx" , new ParsePosition(0) );
// added because SimpleDateFormat.setLenient(boolean lenient) method sucks!
newDate = newDate.equals(new Date(0)) ? null : newDate;
System.out.println("date is " + newDate);
}
}
returned - date is null
Does this method not work or are we going mad and missing something?
For more detail, please look up the key words mentioned in this post in
the Java Glossary at: http://mindprod.com/gloss.html
If you don't see what you were looking for, complain!
or send your contribution for the glossary.
--
Roedy Green, Canadian Mind Products
Custom computer programming since 1963. Ready to take on new work.
You didn't fix "it" you fixed the code that used it.
Might I suggest that you could do the OO thing and change the Object which is broken.
class LentientSimpleDateFormatWhichDoesWhatIWant {
public Date parse( ... )
Date date = super.parse( ... );
if ( date.getTime() == 0 ) {
throw ...
}
}
or maybe check into how ParsePosition works.
Which brings us to RTFM! Since parse( String , ParsePosition ) is not defined to throw anything,
but Parse( String ) is! What did you expect to happen?
Changing the code to call parse( "xxx" );
On my machine results in:
java.text.ParseException: Unparseable date: "xxx"
at java.text.DateFormat.parse(DateFormat.java:324)
at Tmp.main(Tmp.java:20)
Is that what you expected?
What is parse( String, ParsePostion ) designed to do?
If you check the values in ParsePosition you should see
it is now set at zero, i.e. it hasn't consumed any characters. APIs which use of ParsePosition
generally have this behavior. What they do is updated in the ParsePosition. Callers are
supposed to check it. This is exactly what parse( String ) does in order to throw an
exception.
HTH,
-Paul
----
Myriad Genetics: http://www.myriad.com/
Java FAQ: http://www.afu.com/javafaq.html (Section 9, Computer Dating)