?
Solved

Java Date Format

Posted on 2005-04-06
39
Medium Priority
?
538 Views
Last Modified: 2012-06-27
I have a string coming in from a form:

String expiryDate = request.getParameter("expiryDate");


I want to check if the string conforms to the format of:

2005-06-01 (year-month-date)

Can someone please help me to develop a check for this please?
0
Comment
Question by:n_colleran
  • 16
  • 12
  • 8
  • +1
39 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 13717713
String dateString = "2005-06-01" ;

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat( "yyyy-MM-dd" ) ;
boolean valid = false ;
try
{
    sdf.parse( dateString ) ;
    valid = true ;
}
catch( java.text.ParseException ex )
{
    // do nothing, valid is already false :-)
}
0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 13717730
A regex like this:
            
String date = "2005-06-01";
System.out.println( date.matches("[0-9]{4}-[0-9]{2}-[0-1]{2}") ) ;  
0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 13717762
oops typo!
String date = "2005-06-01";
System.out.println( date.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}") ) ;  

needs to be tuned to get things like only 12 months, max 31 days etc, so Tims method may be better for you.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 35

Expert Comment

by:TimYates
ID: 13717820
>> needs to be tuned to get things like only 12 months, max 31 days etc,

leap years, etc ;-)

>> so Tims method may be better for you.

Woo!

;-)
0
 

Author Comment

by:n_colleran
ID: 13717904
Is it possible to then then nest an if statement, basically saying that if the date has not been parsed properly, then to forward back to say a jsp.

would it be of the form

if(valid==false){

 message = "Please enter the correct date format";
 session.setAttribute("message", message);
             RequestDispatcher dispatcher =
                 getServletContext().getRequestDispatcher(
                    "/contract/missingfield.jsp");
             dispatcher.forward(request, response);
}
0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 13717956
if overly verbose....

(we can't have you getting ahead of yourself Timothy....)

;-)
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13717987
>> Is it possible to then then nest an if statement, basically saying that if the date has not been parsed properly, then to forward back to say a jsp.

Yes :-)
0
 

Author Comment

by:n_colleran
ID: 13717991
Sorry, that works perfectly actually, i've tested it. In terms of testing the range of numbers, like you discussed, is that though to implement, ie MM, can't be great than 12?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13718016
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat( "yyyy-MM-dd" ) ;
sdf.setLenient( false ) ;

and it should handle it all for you...
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13718026
>> (we can't have you getting ahead of yourself Timothy....)

ooof!  The Timothy word!  Now I feel naughty ;-)

hahaha
0
 

Author Comment

by:n_colleran
ID: 13718160
Sorry, just wondering, how exactly does:
sdf.setLenient( false ) ;
its checks to see if sdf does not exceed the values?

if this is the case, can I

boolean valid = false ;
try
{
   sdf.setLenient( false );
   valid = true ;            
}
 catch( java.text.ParseException ex )
{      
}


In which case, if it exceeds the maimum values, valid  ==false, in which case I can implement another if statement. Is this right?


if(sdf.setLenient( false ) ;
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13718194
No...

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat( "yyyy-MM-dd" ) ;
sdf.setLenient( false ) ;
boolean valid = false ;
try
{
    sdf.parse( dateString ) ;
    valid = true ;
}
catch( java.text.ParseException ex )
{
    // do nothing, valid is already false :-)
}

0
 
LVL 35

Expert Comment

by:TimYates
ID: 13718205
sdf.setLenient( false ) ;

just makes the date parser not so friendly...  otherwise it tries it's hardest to get dates to match...  ie:  32nd January becomes 1st Feb, etc...
0
 

Author Comment

by:n_colleran
ID: 13718277
Sorry guys, it doesn't seem to be working since I added in that sdf.setLenient(false), I've entered in the 2004-20-56 to check it.

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd" ) ;
      
      sdf.setLenient( false ) ;
      boolean valid = false ;
      try
      {
               sdf.parse( expiryDate ) ;
                valid = true ;            
      }
            
      catch( java.text.ParseException ex )
      {      
      }      
            
      if(valid==false){

             message = "Please enter the correct date format";
             session.setAttribute("message", message);
             RequestDispatcher dispatcher =
                 getServletContext().getRequestDispatcher(
                    "/contract/missingfield.jsp");
             dispatcher.forward(request, response);
}
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13718466
What does it say if you change:

       sdf.parse( expiryDate ) ;

to

       out.println( sdf.parse( expiryDate ).toString() ) ;

?

I guess it's converting it to a valid date :-(
0
 

Author Comment

by:n_colleran
ID: 13718835
Is what it converst to: Sun Sep 25 00:00:00 BST 2005
0
 

Author Comment

by:n_colleran
ID: 13718845
Does that mean that sdf.setLenient( false ) ; will not work?
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13721066
You have to keep these statements  inside the try bolck.So that it throws exception if it is not valid date also
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd" ) ;
sdf.setLenient( false ) ;

I have written this sample program please check it

public class NoDot
{
      public static void main(String[] args)
      {
            String expiryDate = "2004-02-30 ";
            
        boolean valid = false ;
        try
         {
          java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd" ) ;
            sdf.setLenient( false ) ;
            sdf.parse( expiryDate ) ;
            valid = true ;          
          }
                     
        catch( Exception ex )
        {  
                  System.out.println("This is the exception" + ex);
                  //do what ever you want to do here
        }    
         
       
           
}
}
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13721959
koppcha, the problem is that

    2004-20-55

is also a valid date using that...
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13721988
The above code willthrough that as exception since it is not valid
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13722029
Isn't that what is expected?
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13723881
>koppcha, the problem is that

    2004-20-55

is also a valid date using that...


Tim,
I just changed the above code with the date you have given and it throws an exceeption.It wont consider that as valid date.
 
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13724728
>>  You have to keep these statements  inside the try bolck.So that it throws exception if it is not valid date also

No you don't...my code should work (as it works the same as your code)

n_colleran, can you post the code you are running...  According to my tests, my code should work...

0
 
LVL 35

Expert Comment

by:TimYates
ID: 13724729
>> I just changed the above code with the date you have given and it throws an exceeption.It wont consider that as valid date.

Yup I just tested my code, and it works as well...
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13726240
>Yup I just tested my code, and it works as well...
In your earlier posts this is the code given by you.I tired it and it did not work for 2004-20-55 date.I am using java1.4 i am not aware if it changes in JAVA1.5


java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat( "yyyy-MM-dd" ) ;
sdf.setLenient( false ) ;
boolean valid = false ;
try
{
    sdf.parse( dateString ) ;
    valid = true ;
}
catch( java.text.ParseException ex )
{
    // do nothing, valid is already false :-)
}

0
 
LVL 35

Expert Comment

by:TimYates
ID: 13726284
yeah...that works for me in 1.4 too...

it should work in 1.5
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13726487
Hi Tim,
  Thanks for the clarification.I double checked it and it works.
0
 

Author Comment

by:n_colleran
ID: 13726502
No, that code works perfectly. Just a small side question. Is it possible to check if a number has been entered in a text field? TimYates & koppcha, will I divide the points 50/50? I just want to thank you for your time, ye've been a great help
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13726589
Hi n_colleran
Points should go to Tim.I didn't do any big difference.
Thanks for offering though
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13726663
>> Is it possible to check if a number has been entered in a text field?

You can do the same thing with DecimalFormat

Actually...  regex is probably your best bet here:

String value = "14" ;
boolean valid = value.matches( "^\\d+$" ) ;

should do it :-)
0
 
LVL 35

Accepted Solution

by:
TimYates earned 400 total points
ID: 13726676
that string "^\\d+$" basically checks that value looks like this:

    [START_OF_STRING][char 0-9 one or more times][END_OF_STRING]

Which I think is what you want :-)
0
 

Author Comment

by:n_colleran
ID: 13726720
Thank you very much, you really have been a great help to me, thanks again
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13726750
Thanks!  And thanks koppcha! :-)

Good luck!

Tim
0
 

Author Comment

by:n_colleran
ID: 13726756
I've tried to incorporate the number check into my date check, but I receive the error, int cannont be dereferencd. Any ideas?      

boolean valid = false ;
            try
            {
                   premium.matches( "^\\d+$" ) ;
                   sdf.setLenient( false ) ;
                   sdf.parse( effectiveDate ) ;
                sdf.parse( expiryDate ) ;
                valid = true ;            
            }
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13726795
is "premium" an int?

then you know it's a number already...

.matches works on Strings...
0
 

Author Comment

by:n_colleran
ID: 13729315
The value premium is read from a text box from a form, I want to check if it is a number, and if it is, I will assign it as an int:

String premium2 = request.getParameter("premium");
            int premium = 0;
            
 
        boolean number = false ;
            try
            {
               premium2.matches( "^\\d+$" ) ;
                number = true ;            
            int premium = Integer.parseInt(premium2);
            }
            catch( java.text.ParseException ex )
            {      
            }
0
 

Author Comment

by:n_colleran
ID: 13729339
Sorry, this is what I have, I get the error, exception java.text.ParseException is never thrown in body of corresponding try statement:

             String premium2 = request.getParameter("premium");
            int invoiceNo=0;
            int premium=0;
            
        boolean number = false ;
            try
            {
               premium2.matches( "^\\d+$" ) ;
                premium = Integer.parseInt(premium2);
                number = true ;            
            
            }
            catch( java.text.ParseException ex )
            {      
            }
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13729397
ok it throws NumberFormatException not ParseException so change it

String premium2 = request.getParameter("premium");
          int invoiceNo=0;
          int premium=0;
         
        boolean number = false ;
          try
          {
             premium2.matches( "^\\d+$" ) ;
              premium = Integer.parseInt(premium2);
              number = true ;          
         
          }
          catch( NumberFormatException e )
          {    
          }
0
 

Author Comment

by:n_colleran
ID: 13729862
I think thats working, so if it is an incorrect string, the premium will be set to 0. Does that mean I can perform can use it in error checking further like this, where premium is of type int?

if ((effectiveDate.length()==0) || (expiryDate.length()==0 || premium==0)){
message = "Please enter values in all the required fields";
 session.setAttribute("message",       message);
             RequestDispatcher dispatcher =
                 getServletContext().getRequestDispatcher(
                    "/invoice/missingfield.jsp");
             dispatcher.forward(request, response);
        }
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Strategic internal linking is often considered an SEO power technique, especially for content marketing. Do you need to hire an SEO agency to optimize you internal linking? No, this article will help you understand the basics of internal linking and…
MSSQL DB-maintenance also needs implementation of multiple activities. However, unprecedented errors can hamper the database management. In that case, deploying Stellar SQL Database Toolkit ensures fast and accurate database and backup repair as wel…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Suggested Courses

839 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