stephendfrancis
IS-IT--Management
Date parsing seems to be a difficult area in most languages. I'm looking for a reliable way of doing it using standard Java libraries. My current approach is:
...
public static SimpleDateFormat sdf = new SimpleDateFormat( "dd/MM/yyyy" );
...
java.util.Date dDate = sdf.parse( strValue );
where strValue is a String input from the user.
I have two specific questions:
1. if strValue is an invalid date e.g. "29/2/2001", instead of throwing an Exception (which I would prefer) dDate is set to the next appropriate date (i.e. "1/3/2001" in this case). How do I get an Exception if the date is invalid?
2. if strValue has a 2-digit date e.g. "4/4/01", dDate is set to "04/04/0001" - 1 A.D. is really outside the relevant date range for this software...! I know my date format specifies 4 digits, so Java is doing something logical. But is there a way of both allowing 4-digit input (if given), but also determining that a 2-digit year should be of a given century (e.g. 1900s if year >50 and 2000s if year <50) - or in these enlightened post-Y2K days is such a thing frowned upon?
Many thanks...
Stephen.
...
public static SimpleDateFormat sdf = new SimpleDateFormat( "dd/MM/yyyy" );
...
java.util.Date dDate = sdf.parse( strValue );
where strValue is a String input from the user.
I have two specific questions:
1. if strValue is an invalid date e.g. "29/2/2001", instead of throwing an Exception (which I would prefer) dDate is set to the next appropriate date (i.e. "1/3/2001" in this case). How do I get an Exception if the date is invalid?
2. if strValue has a 2-digit date e.g. "4/4/01", dDate is set to "04/04/0001" - 1 A.D. is really outside the relevant date range for this software...! I know my date format specifies 4 digits, so Java is doing something logical. But is there a way of both allowing 4-digit input (if given), but also determining that a 2-digit year should be of a given century (e.g. 1900s if year >50 and 2000s if year <50) - or in these enlightened post-Y2K days is such a thing frowned upon?
Many thanks...
Stephen.