Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Date Parsing in Java

Status
Not open for further replies.

stephendfrancis

IS-IT--Management
Jul 9, 2001
6
GB
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. &quot;4/4/01&quot;, dDate is set to &quot;04/04/0001&quot; - 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.
 
Hi,

You should implement your own logic for that kinds of cases.
Here is one example (far from complete) which may give you an idea.
_____________________________________________
import java.text.*;
import java.util.*;

public class SimpleDF extends SimpleDateFormat
{
public void applyPattern(String pattern_)
{
super.applyPattern(pattern_);

dayStart = pattern_.indexOf(&quot;d&quot;);
monthStart = pattern_.indexOf(&quot;M&quot;);
}

public Date parse(String txt_) throws ParseException
{
Date date = super.parse(txt_);

int dLen = txt_.indexOf(&quot;/&quot;, dayStart);

int days = new Integer(txt_.substring(dayStart, dLen)).intValue();

int mLen = txt_.indexOf(&quot;/&quot;, monthStart);
int m = new Integer(txt_.substring(monthStart, mLen)).intValue()-1;

if(DAYS_IN_MONTH[m] < days)
{
throw new ParseException(&quot;Illegal number of days!!!&quot;, monthStart);
}

return date;
}

private static final int[] DAYS_IN_MONTH = {31,28,31,30,31,30,31,31,30,31,30,31};
private int dayStart;
private int monthStart;
}

__________________________________________________________

previous example works only with separator &quot;/&quot; and the parsed date string must be at form of &quot;dd/mm/yyyy&quot; and much more ;)
...But I think that's the way, override the parse method and handle the string to be parsed....
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top