Home > Enterprise >  how to do a date validation with leap years?
how to do a date validation with leap years?

Time:07-03

I hope you are good! and I hope you can help me with my doubt, thank you very much!

How can I do a date validation with leap years in java? Unfortunately, I can't use regular expressions or calendar. I will explain step by step! I hope you can understand me, if not, I will be waiting for your answers! Regards

This is my main component (where I implement most things): An example of the implement I have to use vvvvv

    private static final Logger LOGGER = LoggerFactory.getLogger(MGBDRVDC.class);
@Override
public Long executeValAccount(Map<String, Object> parameterIn) {
    Long flag = null;
    Utility util = new Utility(); 
    if(util.validateAcc((String) parameterIn.get(Constants.ACCOUNTNUMBER.getValue()))){
        LOGGER.info("Valid Account");

    /// IMPLEMENTATION?
    if(parameterIn.get("date")!=null
            && util.validateDate((String) parameterIn.get(Constants.DATE.getValue()))){
    }else if (util.dateNull((String)parameterIn.get("date")){   
    }

     ////////////////////////////////////////////////       
    
}else {
    this.addAdvice(Constants.MGBD100005.getValue());
    LOGGER.info("Invalid Account");
}

    return flag;

}

enter code here
 
    

and in another component called utility (I put the methods that will be used in the implementation, all this to carry an order, my utility code is as follows:

I put the data separately in a LOCAL ENVIRONMENT online, where I put a date that is valid in any respective year. enter image description here

For example in the image, I am putting the date 02/29/2012 which is validated and is in the correct order, but if I put a date 02/30/2012 which is incorrect data, it will throw me an error called 10005 .

enter image description here

METHODS THAT I USE IN THE PROGRAM (BUT IT STILL DOESN'T COME OUT)

public class Utility {
public boolean validateAcc(String accountNumber){
    return accountNumber!=null && accountNumber !="" 
            && accountNumber.matches(Constants.MATCHES.getValue());
}

**public boolean dateNull(String date){
    return date == null || date == "";
}

public boolean validateDate(final Object parameter){
    return parameter != null;
    
}
public boolean isLeapYear(long prolepticYear){
    return ((prolepticYear % 4 == 0) && (prolepticYear % 100 != 0)) || (prolepticYear % 400 == 0);
    
}

}**

How can I use isleapYear in my implement?

if(parameterIn.get("date")!=null
            && util.validateDate((String) parameterIn.get(Constants.DATE.getValue()))){
    }else if (util.dateNull((String)parameterIn.get("date")){   
    }

PD: I'm open for different answers or methods, THANKS rewards

CodePudding user response:

Since you already have a Utility class, write one more utility method. Now all you have to do is see if the day portion of your date falls in between 1 and maxDays.

public int getMaximumDays(int month, int year) {
    int[] maxDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    if (month < 1 || month > 12) {
        return -1;
    }
    if (month == 2 && isLeapYear(year)) {
        return 29;
    } else {
        return maxDays[month - 1];
    }
}
    

CodePudding user response:

@Gilbert le Blanc

Like this right?

public class Utility {
    public boolean validateAcc(String accountNumber){
        return accountNumber!=null && accountNumber !="" 
                && accountNumber.matches(Constants.MATCHES.getValue());


public int getMaximumDays(int month, int year) {
        int[] maxDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        if (month < 1 || month > 12) {
            return -1;
        }
        if (month == 2 && isLeapYear(year)) {
            return 29;
        } else {
            return maxDays[month - 1];
        }
    }

    private boolean isLeapYear(int year) {
        return false;
    }
}

CodePudding user response:

Here is my implementation (Another component where I command to call my method with its conditions)

    @Override
    public Long executeValAccount(Map<String, Object> parameterIn) {
        Long flag = null;
        Utility util = new Utility(); 
        if(util.validateAcc((String) parameterIn.get(Constants.ACCOUNTNUMBER.getValue()))){
            LOGGER.info("Valid Account");


    /// IMPLEMENTATION? ////////////////////////////////////////////////



     Here I command to call my method to validate it 
      so that when I enter the date, I get a result.
        vvvvvvvvvvvvvvvvvvvvvvvvvvvvv

    **if(parameterIn.get("date")!=null
            && util.validateDate((String) parameterIn.get(Constants.DATE.getValue()))){
    }else if (util.dateNull((String)parameterIn.get("date")){   
    }**



     ////////////////////////////////////////////////       
    
    }else {
        this.addAdvice(Constants.MGBD100005.getValue());
        LOGGER.info("Invalid Account");
    }
    
        return flag;

CodePudding user response:

You can use a method like this to validate your date String. You specify the format you want to validate. Read the method JavaDoc supplied:

/**
 * Check the validity of the supplied date string based on the Date or 
 * Date/Time format you specify. The supplied date string must match 
 * the supplied format in order to be valid.<br><br>
 * 
 * <b>Example Usage:</b><pre>
 * 
 *      System.out.println(isDateStringValid("04/28/2022 13:23:05", 
 *                                           "MM/dd/uuuu HH:mm:ss"));
 * 
 *                               O R
 * 
 *      System.out.println(isDateStringValid("04/28/2022", "MM/dd/uuuu"));</pre>
 * 
 * @param dateTimeString (String) The Date or Date-Time string to validate.<br>
 * 
 * @param desiredFormat (String) The date or date-time format expected.<br><br>
 * 
 * <b><u>Note:</u></b> This method utilizes the <b>java.time.format.DateTimeFormatter</b> class. It 
 * should be realized that for most cases, when providing Pattern Letters to 
 * represent year, you will want to use "uuuu" (for year) instead of "yyyy" 
 * (for year-of-era). There is a significant difference between the two Pattern 
 * Letters which you can read about here:<pre>
 * 
 *  https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
 * 
 *  and in Detail here:
 * 
 *  https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoField.html#YEAR_OF_ERA</pre>
 * 
 * @return (boolean) True is returned if the supplied date or date-time string 
 * is valid and boolean false if it is not.
 */
public static boolean isDateStringValid(String dateTimeString, String desiredFormat) {
    boolean result = true;
    java.time.format.DateTimeFormatter formatter = 
            java.time.format.DateTimeFormatter.ofPattern(desiredFormat)
                    .withResolverStyle(java.time.format.ResolverStyle.STRICT);
    try {
        if ((dateTimeString.contains(":") && !desiredFormat.contains(":")) || 
                (!dateTimeString.contains(":") && desiredFormat.contains(":"))){
            return false;
        }
        else if (dateTimeString.contains(":") && desiredFormat.contains(":")) {
            java.time.LocalDateTime localDate = java.time.LocalDateTime.parse(dateTimeString, formatter);
        }
        else {
            java.time.LocalDate localDate = java.time.LocalDate.parse(dateTimeString, formatter);
        }
    } 
    catch ( java.time.format.DateTimeParseException dtpe) {
        result = false;
    }
    return result;
}

EDIT: As per comments:

I should think that you would place this method into the Utility class. To use this method for your particular use-case, I believe it would be:

if(parameterIn.get("date") != null
        && util.isDateStringValid((String) parameterIn.get(Constants.DATE.getValue()), "MM/dd/uuuu")) {

}
else if (util.dateNull((String)parameterIn.get("date")){   

}
  •  Tags:  
  • java
  • Related