Comparando Date utilizando Date.before () y Date.after () Métodos en Java

Date.before () y Date.after () en Java: en este programa, que están tomando dos fechas de entrada y la comparación de fechas usando Date.before () y Date.after () métodos.

Dada (entrada) dos fechas en formato de cadena, los convierten en formato de fecha y luego compararlas utilizando Date.before () y Date.after () de Java.

1) Date1.before (Date2) Método

Se devuelve verdadero si Fecha1 es menor que Date2.

2) Date1.after (Date2) Método

Se devuelve verdadero si Fecha1 es mayor que Date2.

Considere el programa:


import java.text.SimpleDateFormat;
import java.util.*;
public class p22
{
public static void main(String args[])
{
try
{
//define date format to take input
SimpleDateFormat dateF = new SimpleDateFormat("dd/MM/yyyy");
Scanner sc=new Scanner(System.in); //string object
String dtString1="",dtString2="";
System.out.print("Enter first date in dd/MM/yyyy format:");
dtString1=sc.nextLine();
System.out.print("Enter second date in dd/MM/yyyy format:");
dtString2=sc.nextLine();
//convert input date string into Date
Date dt1= dateF.parse(dtString1);
Date dt2= dateF.parse(dtString2);
System.out.println("First Date is: " + dt1.toString());
System.out.println("Second Date is: " + dt2.toString());
if( dt1.after(dt2)){
System.out.println(dt1.toString() +" is greater than "+ dt2.toString());
}
else if(dt1.before(dt2)){
System.out.println(dt1.toString() +" is less than "+ dt2.toString());
}
else{
System.out.println(dt1.toString() +" is equal to "+ dt2.toString());
}
}
catch(Exception e) {
System.out.println("Exception is: "+ e.toString());
}
}
}

salida

First Run:
Enter first date in dd/MM/yyyy format:21/08/2009
Enter second date in dd/MM/yyyy format:21/09/2008
First Date is: Fri Aug 21 00:00:00 IST 2009
Second Date is: Sun Sep 21 00:00:00 IST 2008
Fri Aug 21 00:00:00 IST 2009 is greater than Sun Sep 21 00:00:00 IST 2008
Second Run:
Enter first date in dd/MM/yyyy format:21/08/2008
Enter second date in dd/MM/yyyy format:21/08/2009
First Date is: Thu Aug 21 00:00:00 IST 2008
Second Date is: Fri Aug 21 00:00:00 IST 2009
Thu Aug 21 00:00:00 IST 2008 is less than Fri Aug 21 00:00:00 IST 2009
Third Run:
Enter first date in dd/MM/yyyy format:21/08/2008
Enter second date in dd/MM/yyyy format:21/08/2008
First Date is: Thu Aug 21 00:00:00 IST 2008
Second Date is: Thu Aug 21 00:00:00 IST 2008
Thu Aug 21 00:00:00 IST 2008 is equal to Thu Aug 21 00:00:00 IST 2008


Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *