Solved

Validating a date

Posted on 2001-08-11
13
384 Views
Last Modified: 2010-03-31
What is the best way to validate a date that has been entered as a string?

I've been playing with Date() and SimpleDateFormat() and get totally confused when it comes to the Calendar class so any pointers greatly appreciated.
0
Comment
Question by:ssherlock
  • 5
  • 4
  • 2
  • +2
13 Comments
 

Expert Comment

by:ksalman
ID: 6376082
Try something like this.

  DateFormat df = DateFormat.getDateInstance();
  myDate = df.parse(myString);
0
 
LVL 92

Expert Comment

by:objects
ID: 6376595
What format is your date string in?
0
 

Author Comment

by:ssherlock
ID: 6376733
For examplepurposes I am doing the following:
    SimpleDateFormat dfgmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    String startDate = "32-02-2001 12:15:12"; //Invalid date

    Date testDate = new Date(dfgmt.parse(startDate).getTime());
    String testString = dfgmt.format(testDate);

I want the above to somehow tell me that the date is invalid rather than just work something out.  

I've just had this horrid thought that you're going to mention Timezones :))  
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 92

Expert Comment

by:objects
ID: 6376751
Looks like it's not doing any number verification.
Though I thought it should?

It'll already be taking your TimeZone into consideration.
0
 
LVL 2

Expert Comment

by:vasan_sr
ID: 6376896
the best way is to use simple date format....
0
 

Author Comment

by:ssherlock
ID: 6376910
vasan_ar said:
>the best way is to use simple date format....

But that's what I am doing - see the example above.  Entering the incorrect date given just returns 04-03-2001 rather than an error.  I need to be able to trap an error when a user enters a date that is so obviously invalid.
0
 

Expert Comment

by:ksalman
ID: 6377136
The parse will throw an parseException when there is something wrong with the date and thats you can trap the error.
0
 

Author Comment

by:ssherlock
ID: 6377254
Sorry if I'm being dense but wrapping the parse in a try catch with parseException says the class can't be found.  Using ParseException (note the capital P) and it works as before.  I'm sure I'm doing something wrong.  The code is as follows:
    try
    {
      Date testDate = new Date(dfgmt.parse(startDate).getTime());
      String testString = dfgmt.format(testDate);
      JLabel dateLabel = new JLabel(testString);
      contentPane.add(dateLabel);
    }
    catch (parseException e)
    {
      JLabel dateLabel = new JLabel("There was an error with the date");
      contentPane.add(dateLabel);
    }
0
 
LVL 4

Expert Comment

by:k.jones
ID: 6380716
You want to use the 'setLenient(false)' method of Calendar and SimpleDateFormat classes.  If you do not set to false, then the class will make a best effort to interpret invalid dates such as "32-02-2001 12:15:12" rather than throwing the exception that you would like.

Cheers,
Ken Jones
0
 

Author Comment

by:ssherlock
ID: 6381035
Can you point me towards any examples?

Thanks, Simon
0
 

Expert Comment

by:ksalman
ID: 6381124
Here is a sample code:

import java.text.DateFormat;
import java.text.ParseException;
import java.util.*;


public class Test
{
     public static void main(String args[])
     {
   try
   {
         String startDate = "03/30/00 1:43 PM";    

      Date now = new Date();
      DateFormat df = DateFormat.getDateInstance();
      DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
      DateFormat df2 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
      DateFormat df3 = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
      DateFormat df4 = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
      String s = df.format(now);
      String s1 = df1.format(now);
      String s2 = df2.format(now);
      String s3 = df3.format(now);
      String s4 = df4.format(now);

      System.out.println("(Default) Today is " + s);
      System.out.println("(SHORT) Today is " + s1);
      System.out.println("(MEDIUM) Today is " + s2);
      System.out.println("(LONG) Today is " + s3);
      System.out.println("(FULL) Today is " + s4);
   
      df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
      df.setLenient(false);
      Date testDate = new Date(df.parse(startDate).getTime());
      String testString = df.format(testDate);
       System.out.println("test:" + testString);
     }
   catch (ParseException e)
   {
   System.out.println("test:" + e);
   }
     }
}

For more details you can also look at this Java World article

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-dates.html

HTH

0
 

Author Comment

by:ssherlock
ID: 6385727
ksalman,
Thanks. That was excellent and helped a lot.  As did the pointer to the web article.  Please submit your post as the answer.
Cheers, Simon.
0
 

Accepted Solution

by:
ksalman earned 50 total points
ID: 6385795
Resubmitting as Answer as per ssherlock request.

Here is a sample code:

import java.text.DateFormat;
import java.text.ParseException;
import java.util.*;


public class Test
{
    public static void main(String args[])
    {
  try
  {
        String startDate = "03/30/00 1:43 PM";    

     Date now = new Date();
     DateFormat df = DateFormat.getDateInstance();
     DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
     DateFormat df2 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
     DateFormat df3 = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
     DateFormat df4 = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
     String s = df.format(now);
     String s1 = df1.format(now);
     String s2 = df2.format(now);
     String s3 = df3.format(now);
     String s4 = df4.format(now);

     System.out.println("(Default) Today is " + s);
     System.out.println("(SHORT) Today is " + s1);
     System.out.println("(MEDIUM) Today is " + s2);
     System.out.println("(LONG) Today is " + s3);
     System.out.println("(FULL) Today is " + s4);
 
     df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
     df.setLenient(false);
     Date testDate = new Date(df.parse(startDate).getTime());
     String testString = df.format(testDate);
      System.out.println("test:" + testString);
    }
  catch (ParseException e)
  {
  System.out.println("test:" + e);
  }
    }
}

For more details you can also look at this Java World article

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-dates.html

HTH

0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
what is a "java.lang.System Property"   ? 20 65
Java Options in Zimbra Server 2 50
java jdbc batch example 8 29
hibernate jars 4 26
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

815 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now