Solved

Validating a date

Posted on 2001-08-11
13
370 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
 
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
bigHeights  challenge 13 56
strDist challenge 35 84
Modeling a class in java 5 34
create a gui in perl 3 46
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

744 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

13 Experts available now in Live!

Get 1:1 Help Now