0

A user enters his birth date in a jTextfield in the yyyy/mm/dd and I want to make sure that he enters it correctly like that and also that it is a real date. this is my code so far:

SimpleDateFormat df = new SimpleDateFormat("yyyy/mm/dd");  
Date testDate = null;

Birth = jTextField3.getText();

try{  
    testDate = df.parse(Birth);
} catch (ParseException e){ }      
if (!df.format(testDate).equals(Birth)){  
    JOptionPane.showMessageDialog(rootPane, "invalid date!!");
}

the error I am getting is it said I cant cast a java.sql.Date into a java.util.Date

tbodt
  • 16,609
  • 6
  • 58
  • 83
mike157
  • 63
  • 3
  • 14

2 Answers2

6

mm is minutes. MM is months:

SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

See the documentation for more details.

You should set that to be strict (df.setLenient(false), and then you don't need to try to format the result again - just the parse exception should be enough.

Personally I'd use Joda Time for any date/time work in Java though - it's a much nicer API.

As for java.util.Date vs java.sql.Date - the code you've given us would entirely use java.util.Date. If you've already got an import for java.sql.Date which you want to preserve, you'd want something like:

java.util.Date testDate = ...;

Although as you don't need to reformat it, you may not even need a variable at all:

SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
df.setLenient(false);
Date testDate = null;
boolean valid = false;
try {
    df.parse(jTextField3.getText());
    valid = true;
}
catch (ParseException e) { } // valid will still be false
if (!valid) {  
    JOptionPane.showMessageDialog(rootPane, "invalid date!!");
}

(Or you could show the message dialog in the catch block, but then you can't easily have an else clause for the success case...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @mike157: Ah, now you've actually given us an *error*, I'll edit my answer. Until that point, you'd *only* shown us the code - so I was only able to correct what was broken. – Jon Skeet Aug 04 '13 at 07:28
1

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Apart from this, there are many other problems with your code:

  1. Never use SimpleDateFormat or DateTimeFormatter without a Locale.
  2. The letter, m specifies the minute-of-hour while the letter, M specifies the month-of-year and you have used m for the month-of-year.
  3. Never let your code swallow exceptions. Your code, catch (ParseException e){ } will simply swallow the exception refuting the purpose of this important feature. Either handle the exception or let your method throw it so that the caller of the method can handle it appropriately. In order to do it, you need to add throws ParseException to your method signature.
  4. You have not followed the Java naming conventions according to which the variable, Birth should be named as birth. Even though it won't cause any error, your code may confuse others.

Solution using java.time, the modern Date-Time API:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;

import javax.swing.JOptionPane;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u/M/d", Locale.ENGLISH);
        LocalDate date = null;

        // In your code it will be: String birth = jTextField3.getText();
        String birth = JOptionPane.showInputDialog(null, "Enter date in the format yyyy/MM/dd: ");

        try {
            date = LocalDate.parse(birth, dtf);
            JOptionPane.showMessageDialog(null, date, "Alert", JOptionPane.WARNING_MESSAGE);
        } catch (DateTimeParseException e) {
            JOptionPane.showMessageDialog(null, "Invalid date!!");
        }
    }
}

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110