Had an assigment making a bankaccount, and validating the account owners age, this is just a bit of the code.....

public boolean checkDate(String myDate) // my date should be in the format 20111224 
    {
        int year = Integer.parseInt(myDate.substring(0, 4));// convert the year 2011 to int
        int month = Integer.parseInt(myDate.substring(4,6)); //convert the month 12 to int
        int day = Integer.parseInt(myDate.substring(6)); // convert the day 24 to int

        if (year >=1900 && year < 2012)  //test of the year
        {
            System.out.println("Year is ok");                    

            if (month >= 1 && month <= 12)
            {
                system.out.println("Month is OK");

            }            
            if ((month = 1)&&(day >= 1 && day <=31))
            {
                System.out.println("Day is OK");
            }
            if ((month = 2)&&(day >= 1 && day <=29))
            {
                System.out.println("Day is OK");
            }
            if ((month = 3)&&(day >= 1 && day <=31)) 
            {
                System.out.println("Day is OK");                             
            }
            if ((month = 4)&&(day >= 1 && day <=30))
            {
                System.out.println("Day is OK");
            }
            if ((month = 5)&&(day >= 1 && day <=31))
            {
                System.out.println("Day is OK");
            }
            if ((month = 6)&&(day >= 1 && day <=30))
            {
                System.out.println("Day is OK");
            }
            if ((month = 7)&&(day >= 1 && day <=31))
            {
                System.out.println("Day is OK");
            }
            if ((month = 8)&&(day >= 1 && day <=31))
            {
                System.out.println("Day is OK");
            }
            if ((month = 9)&&(day >= 1 && day <=30))
            {
                System.out.println("Day is OK");
            }
            if ((month = 10)&&(day >= 1 && day <=31))
            {
                System.out.println("Day is OK");
            }
            if ((month = 11)&&(day >= 1 && day <=30))
            {
                System.out.println("Day is OK");
            }
            if ((month = 12)&&(day >= 1 && day <=31))
            {
                System.out.println("Day is OK");
                return true;
            }

Question: there must be a easyer way to validate that month and day match. Examble Febuary 29 or June 30 is true and june 31 and febuary 31 is false. Leape year not countet.
Only been programming for 8weeks, so pls dont yell at me, if i seem like an airhead for not understanding this. It just seem strange that i had to make 12 'ifs' there must be a simple way, an algoritme for this problem.

i was thinking something like:

if (month == 1,3,5,7,8,10,12) && (day >=1 && day<=31); return true;
an so on..... Why not?? remember im a noob

Dani AI

Generated

Good instincts. The long chain of ifs is hard to read and easy to break. Two quick fixes to your approach: (1) use equality == in conditions, not assignment =; and (2) avoid repeating logic. A tiny lookup table makes this simple, just as suggested. Also, as noted, watch 1-based months versus 0-based arrays.

// Feb is capped at 29 because you said "ignore leap year"
private static final int[] DAYS_IN_MONTH = {
    0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};

static boolean isValidYyyyMmDd(String s) {
    if (s == null || s.length() != 8 || !s.chars().allMatch(Character::isDigit)) return false;
    int y = Integer.parseInt(s.substring(0, 4));
    int m = Integer.parseInt(s.substring(4, 6));
    int d = Integer.parseInt(s.substring(6, 8));
    if (y < 1900) return false;               // adjust to your business rules
    if (m < 1 || m > 12) return false;
    return d >= 1 && d <= DAYS_IN_MONTH[m];
}

For production code, let the library validate the calendar rules (including real leap years). This also makes age checks trivial for a bank KYC rule like "must be 18+".

import java.time.*;
import java.time.format.*;

static boolean isAdult(String s) {
    DateTimeFormatter f = DateTimeFormatter.ofPattern("uuuuMMdd")
                                           .withResolverStyle(ResolverStyle.STRICT);
    LocalDate dob = LocalDate.parse(s, f);    // throws if date is invalid
    return Period.between(dob, LocalDate.now()).getYears() >= 18;
}

Tip: use early returns (as above) to keep the code linear, and prefer a single source of truth (the table or the library) instead of many conditionals. This reduces bugs and makes the code easy to test.

Recommended Answers

All 2 Replies

if (month == 1 || month == 3 || ...
or you could do an array of months holding the number of days...
int[] daysInMonth = (31, 29, 31, 30 ...
then look up the number of days using the month number as index.
Either way, you'll have to special-case Feb!

There are many ways some better some worst for checking date validity and you will learn them later.
James already showed two possibilities (second is much better, considering that you are taking month from 1 to 12, where array starts from 0 to size -1. Just keep that in mind)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.