-3

Total newbie in programming: Need to get user to enter date in (mm/dd/yyyy) format. Need to parseInt() the String and validate whether it is Valid or Invalid Date.
Please help.
To program using java.

import java.util.Scanner;

public class ct0280642Assignment
{
    public static void main(String [] dateValidation)
    {
        Scanner kb = new Scanner(System.in);
        System.out.println("Please enter a date (mm/dd/yyyy)");
        String uDate = kb.nextLine();
        int userDate = Integer.parseInt(uDate);
        int length = uDate.length();

        if(length != 10)
        {
            System.out.println(uDate+" is a not valid Date");
        }
        else
        {
            System.out.println(uDate+" is a valid Date");
        }
    }    

}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 1
    Date validation or only length validation? – Sagar Gangwal Jun 22 '17 at 10:12
  • 3
    "Need to parseInt()" - why? Why not use the built-in date parsing functionality? Is this because the assignment is specifically *about* parsing? If so, you'll need to: 1) Split the input into components; 2) Parse each part as an integer; 3) Validate that the components make sense (e.g. not 30th February). Please be specific about what part of that is causing problems. (At the moment it looks like you're trying to parse the whole thing as one integer...) – Jon Skeet Jun 22 '17 at 10:15
  • Newbie to your search engine too? ;-) Please train your use of that and you may not need ask. – Ole V.V. Jun 22 '17 at 10:43
  • You require two digit month and day, as in 06/22/2017 or 07/02/2017? Any particular reason you don’t want to allow one digit? Thinking it could be convenient for the user and unambiguous. – Ole V.V. Jun 22 '17 at 11:26
  • 1
    Search Stack Overflow thoroughly before posting. – Basil Bourque Jun 22 '17 at 16:20

3 Answers3

1
import java.util.Scanner;

public class ct0280642Assignment {
    public static void main(String[] dateValidation) {
        Scanner kb = new Scanner(System.in);
        System.out.println("Please enter a date (mm/dd/yyyy)");
        String uDate = kb.nextLine();
        int userDate = Integer.parseInt(uDate);
        int length = uDate.length();

        try {
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
            df.setLenient(false);
            df.parse(uDate);
            System.out.println(uDate + " is a not valid Date");

        } catch (ParseException e) {
            System.out.println(uDate + " is a valid Date");
        }
    }

}

Try above code.

Here i had used DateFormat function and try to parse that String using df.parse(uDate).If date is valid it automatically transfer that string into DATE.

If there is some issue with that string automatically that will generate exception and will be handle by ParseException and write message date is not valid.

Hope this will help you.

Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38
1

Try the below code. SimpleDateFormat will parse the given date and throws Exception if input is not valid.

public static void main(String [] dateValidation)
    {
        Scanner kb = new Scanner(System.in);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        sdf.setLenient(false);
        System.out.println("Please enter a date (mm/dd/yyyy)");
        String uDate = kb.nextLine();
        try{
            sdf.parse(uDate);
            System.out.println(uDate+" is a valid Date");
        }
        catch(Exception e)
        {
            System.out.println(uDate+" is not a valid Date");
        }
        kb.close();
    }  

Find the link for documentation on SimpleDateFormat here.

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

M.Navy
  • 155
  • 7
  • 2
    Please, don’t teach the young ones to use the long outdated `SimpleDateFormat` class. `DateTimeFormatter` is much better. – Ole V.V. Jun 22 '17 at 10:56
  • @OleV.V. We can use DateTimeFormatter but it is only available in Java 8. So let the young ones to learn without struggling if they use Java 7 or lower versions. – M.Navy Jun 22 '17 at 11:08
  • 2
    First, the young ones ought to use Java 8 (or later) to get as close to their future as possible. Second, the modern classes are available in Java 6 and 7 through [the ThreeTen Backport](http://www.threeten.org/threetenbp/). – Ole V.V. Jun 22 '17 at 11:18
1

A common way to validate user input is by trying to parse it and seeing if that succeeds. That also works here. Java has nice built-in facilities for parsing dates in various fixed formats, so I suggest you use these:

private static final DateTimeFormatter PARSE_FORMATTER
        = DateTimeFormatter.ofPattern("MM/dd/uuuu");

public static void main(String [] dateValidation)
{
    try (Scanner kb = new Scanner(System.in)) {
        System.out.println("Please enter a date (mm/dd/yyyy)");
        String uDate = kb.nextLine();
        try {
            LocalDate.parse(uDate, PARSE_FORMATTER);
            System.out.println(uDate + " is a valid Date");
        } catch (DateTimeParseException dtpe) {
            System.out.println(uDate + " is a not valid Date");
        }
    }
}  

This accepts 06/17/2017 but rejects 6/17/2017 because the month hasn’t got two digits. Beware that the format pattern string MM/dd/uuuu is case sensitive (it has to be uppercase M and lowercase d and u).

If you want to allow one-digit months and days, change the formatter to

private static final DateTimeFormatter PARSE_FORMATTER 
        = DateTimeFormatter.ofPattern("M/d/uuuu");

Now all of 7/2/2017, 07/02/2017 and 12/25/2017 are accepted.

Not related to your question, I have used try-with-resources for making sure the Scanner is closed after use. This also closes standard input.

Question: does this work in Java 8 only? No, the modern date and time API that I am using has been backported to Java 6 and 7 in ThreeTen Backport and especially for Android in ThreeTenABP (and then of course it works in Java 9, due this summer, and later versions…).

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161