-1

I am not exactly sure how this is called and how it should be done, but I am learning Java and my assignment is to create a data class that will be able to add days to certain date and subtract and show the difference and so on. My current issue is that I want to implement a rule for every month of the year, I am sure this can be done differently, but I want to try and do this.

Let us say we are given the date in format Year, month, day. 2017.09.31 I want to check before it is printed if month 09 is allowed to have 31 days. So I wanted to go and write this:

if (MM==1 || MM==01);

where MM is month, to say that the value of day for MM can be in a range from 1-30, if the number D is in that range print the number D. Is there any function in Java that lets u use range in this manner?

Ryne Ignelzy
  • 137
  • 1
  • 2
  • 13
  • Is the format always in this form `YYYY.MM.DD`? or there can be `/` slash instead of dot..etc? – Yahya May 19 '17 at 13:23
  • 1
    parse to Integer, check NumberFormatExcpetions, then do the if statement with >0,<31 – JacksOnF1re May 19 '17 at 13:23
  • My tutor said for this assignment we will just have yyyy.mm.dd format but both mm and dd can have just one value – Ryne Ignelzy May 19 '17 at 13:24
  • 1
    Possible duplicate of [Java check if number in interval](http://stackoverflow.com/questions/9532254/java-check-if-number-in-interval) – pedro May 19 '17 at 13:31
  • 2
    Hint: just start coding. Don't come here and ask questions before you tried anything. Learning to program is not about the *solution*, but about the **long hard** way to get there. Trial and error in other words. Feel free to put up a question that contains code, and a clear problem description ( see [mcve] ). But *learning* will be much more efficient for you ... by trying to do this yourself. – GhostCat May 19 '17 at 13:36
  • Have you decided a data type for `MM`? I would suggest `int`. Then it’s not so hard. BTW, a variable name in Java begin with a lowercase letter, so it should probably be `mm` or maybe preferably `month`. – Ole V.V. May 19 '17 at 15:10
  • You may want to use a `switch` statement to distiguish the 12 possible (allowed) values of `MM`. – Ole V.V. May 19 '17 at 15:12
  • For the range check, just use `dd >= 1 && dd <= 30` (assuming `dd` is numeric). – Ole V.V. May 19 '17 at 16:20

3 Answers3

0

You may have a look at this example and create your own one, please keep in mind that we learn via practicing and training.

import java.util.Calendar;
import java.util.Scanner;

public class DateValidation {

    public static void main(String[] args) {
        Scanner in = new Scanner (System.in);
        System.out.println("Enter the date of this format [YYYY.MM.DD]"); // or what ever format you need (don't forget to change the pattern)
        String date = in.nextLine(); //read the entire line
        if(isValidDate(date, "\\.")){
            System.out.println("Valid Date");
        }
        else{
            System.out.println("Invalid Date");
        }
    }

    public static boolean isValidDate(String date, String pattern){
        String[] dateComponents  = date.split(pattern); // split the date String according to the pattern which is in your case a dot .
        // you know that you should have only THREE indices in the array, so check first
        if (dateComponents.length==3){ // if so go ahead
            // now take the Integer value for every subString at every index and parse it
            int year, month, day;
            try{ // wrap with try-catch block in case if there is illegal input (number format)
                year = Integer.parseInt(dateComponents[0]);
                month = Integer.parseInt(dateComponents[1]);
                day = Integer.parseInt(dateComponents[2]);
                if(year>Calendar.getInstance().get(Calendar.YEAR) || dateComponents[0].length()<4 ||
                                    (month>12||month<1) || (day>31||day<1)){ // your validation, you can change , add or remove from them
                    return false;

                }
            }catch(NumberFormatException e){
                return false;
            }
            return true;

        }
        return false;
    }           
}

Test

Enter the date of this format [YYYY.MM.DD]
2017.01.01  ->  Valid Date
2018.01.01  ->  Invalid Date (now we are in 2017)
2016.13.01  ->  Invalid Date (max months is 12)
2015.12.0   ->  Invalid Date (min days is 1)
Just Text   ->  Invalid Date (not a date)
Yahya
  • 13,349
  • 6
  • 30
  • 42
0

The way i did this in the end was the following:

public void setDate (int y, int m, int d){
        YYYY = y;
        MM = ((m>=1 && m<=12) ? m : 1);

        int [] month = {31, 28+(YYYY%4==0?1:0), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        if( d>0 && d<=month[MM-1] ) {
            DD = d;
        } else {
            DD = 1;
        }
Ryne Ignelzy
  • 137
  • 1
  • 2
  • 13
0

java.time

Perhaps not appropriate for your homework, but Java does offer the java.time classes for such work. Specifically, the YearMonth class.

YearMonth.of(
    LocalDate.parse(
        "2017.09.31".replace( "." , "-" )
    )
).lengthOfMonth() == 31

If that day-of-month component might be invalid, then extract the year and month parts to construct a YearMonth object.

YearMonth.parse(
    "2017.09.31".substring( 0, 6 ).replace( "." , "-" )
).lengthOfMonth()

To manage your rules, your number of days to add per month, you can use an EnumMap with the Month enum found in java.time.

Map< Month , Integer > rules = new EnumMap<>() ;

rules.put( Month.JANUARY , 3 ) ;
rules.put( Month.FEBRUARY , 7 ) ;
…
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154