📌  相关文章
📜  .java: Programa al que le indique una fecha dando día, mes y año y te diga si la fecha es Correcta o no y en caso de que lo sea te la indique con el mes en forma de texto. (1)

📅  最后修改于: 2023-12-03 14:38:46.580000             🧑  作者: Mango

Java Program that determines if a given date is valid and converts the month to text

Here's a Java program that checks if a date is valid (given the day, month, and year as input) and converts the month to text if the date is valid.

import java.text.DateFormatSymbols;

public class DateValidation {
    public static void main(String[] args) {
        int day = 15;
        int month = 2;
        int year = 2022;
        
        String result = validateAndConvertDate(day, month, year);
        System.out.println(result);
    }
    
    public static String validateAndConvertDate(int day, int month, int year) {
        if (isValidDate(day, month, year)) {
            String monthText = new DateFormatSymbols().getMonths()[month - 1];
            return String.format("The date is valid. Converted month: %s", monthText);
        } else {
            return "The date is not valid.";
        }
    }
    
    public static boolean isValidDate(int day, int month, int year) {
        if (year < 1 || month < 1 || month > 12 || day < 1) {
            return false;
        }
        
        int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        
        if (isLeapYear(year)) {
            daysInMonth[1] = 29;
        }
        
        return day <= daysInMonth[month - 1];
    }
    
    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
}

Markdown:

## Java Program that determines if a given date is valid and converts the month to text

Here's a Java program that checks if a date is valid (given the day, month, and year as input) and converts the month to text if the date is valid.

**Input:**
```java
int day = 15;
int month = 2;
int year = 2022;

Output:

The date is valid. Converted month: February
Code Explanation

The validateAndConvertDate method first checks if the given date is valid using the isValidDate method. If the date is valid, the monthText is obtained using the DateFormatSymbols class, and the result is formatted. If the date is not valid, an appropriate message is returned. The isValidDate method checks for various conditions like checking if the year, month, and day are within valid ranges and accounts for leap years. The isLeapYear method determines if a given year is a leap year or not.

Note: This program assumes that the date is in the Gregorian calendar.

To use this program, modify the day, month, and year variables in the main method as per your requirements.