Advertisement
robeeeert

VALIDAR FECHA

Jun 14th, 2023
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.84 KB | None | 0 0
  1. import java.util.*;
  2. public class ValFecha {
  3.     public static void main(String[] args) {
  4.         Scanner entrada = new Scanner(System.in);
  5.         System.out.println("Ingrese fecha dd/mm/yyyy");
  6.         String fecha = entrada.nextLine();
  7.         while(!validarFecha(fecha)) {
  8.             System.out.println("Fecha no valida");
  9.             System.out.println("Ingrese nuevamente la fecha dd/mm/yyyy");
  10.             fecha = entrada.nextLine();
  11.         }
  12.         System.out.println("Fecha CORRECTA");
  13.     }
  14.     public static boolean validarFecha(String fecha) {
  15.         String[] partesFecha = fecha.split("/");
  16.         int dia = Integer.parseInt(partesFecha[0]);
  17.         int mes = Integer.parseInt(partesFecha[1]);
  18.         int anio = Integer.parseInt(partesFecha[2]);
  19.         boolean esValida = true;
  20.         if(fecha.length() >10) {
  21.             esValida = false;
  22.         }
  23.         if (mes < 1 || mes > 12){
  24.             esValida = false;
  25.         } else {
  26.             switch (mes) {
  27.                 case 2:
  28.                     if (esBisiesto(anio)) {
  29.                         if (dia < 1 || dia > 29) {
  30.                             esValida = false;
  31.                         }
  32.                     } else {
  33.                         if (dia < 1 || dia > 28) {
  34.                             esValida = false;
  35.                         }
  36.                     }
  37.                     break;
  38.                 case 4: case 6: case 9: case 11:
  39.                     if (dia < 1 || dia > 30) {
  40.                         esValida = false;
  41.                     }
  42.                     break;
  43.                 default:
  44.                     if (dia < 1 || dia > 31) {
  45.                         esValida = false;
  46.                     }
  47.                     break;
  48.             }
  49.         }
  50.         return esValida;
  51.     }
  52.     public static boolean esBisiesto(int anio) {
  53.         return (anio % 4 == 0 && anio % 100 != 0) || (anio % 400 == 0);
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement