Hi,
I'am trying to check if the given date is a valid with the following code.
Is this the right way of doing this?
If so,after I get the day, month and year values using the FieldPosition object, is there a built in java method, which tells me that the given String date is a valid date.
One more problem I have with this is, if I enter the date 02/0398/199999, it should give me the exception.But this code parses this date and gives the output for month=3,day=4,year=200000.
But according to the requirement, that should be invalid date.
If this is not the right way, how can I proceed to achieve my results .Please get me the clue about what all the methods i need to use and what is the sequence.May be Calendar method or something else.
public class hello extends HttpServlet {
String sDate="02/0398/199999"; Date date;
int MONTH; int DAY; int YEAR;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
// DatePattern datepattern;
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
SimpleDateFormat dateformat = new SimpleDateFormat("MM/dd/yyyy");
try{
date = dateformat.parse(sDate);
out.println("date is parsed" + date);
}
catch (ParseException ee) {
out.println(ee.getMessage());
}
FieldPosition posMonth = new FieldPosition(DateFormat.MONTH_FIELD);
FieldPosition posDay = new FieldPosition( DateFormat.DATE_FIELD);
FieldPosition posYear = new FieldPosition(DateFormat.YEAR_FIELD);
StringBuffer yearBuf = new StringBuffer();
StringBuffer monthBuf = new StringBuffer();
StringBuffer dayBuf = new StringBuffer();
try{
yearBuf = dateformat.format(date,yearBuf,posYear);
monthBuf = dateformat.format(date, monthBuf, posMonth);
dayBuf = dateformat.format(date, dayBuf, posDay);
}
catch (Exception ex1) {
out.println(ex1.getMessage());
}
int mBegin = posMonth.getBeginIndex();
int mEnd = posMonth.getEndIndex();
int dBegin = posDay.getBeginIndex();
int dEnd = posDay.getEndIndex();
int yBegin = posYear.getBeginIndex();
int yEnd = posYear.getEndIndex();
try{
MONTH = Integer.parseInt(monthBuf.substring(mBegin, mEnd));
DAY = Integer.parseInt(dayBuf.substring(dBegin, dEnd));
YEAR = Integer.parseInt(yearBuf.substring(yBegin, yEnd));
}
catch(Exception ne)
{
out.println(ne.getMessage());
}
int mEntered = 0;
int dEntered = 0;
int yEntered = 0;
// traps a number format exception if syntax is bad
try{
mEntered = Integer.parseInt(sDate.substring(mBegin, mEnd));
dEntered = Integer.parseInt(sDate.substring(dBegin, dEnd));
yEntered = Integer.parseInt(sDate.substring(yBegin, yEnd));
}
catch (Exception nee)
{
out.println(nee.getMessage());
}
if ( YEAR == yEntered && DAY == dEntered && MONTH == mEntered )
{
}
}
}