Answers for "compareTo method for date"

0

How to compare two string dates using the compareTo method?

package javaapplication;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaApplication {

    public static void main(String args[]) {

        String fromDateString = "2021-06-15";
        
        String toDateString = "2021-07-15";

        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            Date dateFrom = dateFormat.parse(fromDateString);
            
            Date dateTo = dateFormat.parse(toDateString);
            
         
            if (dateFrom.compareTo(dateTo) > 0) {
                System.out.println("From Date is greater than To Date");
                
            } else if (dateFrom.compareTo(dateTo) < 0) {
                
               System.out.println("From Date is less than To Date");
               
            } else if (dateFrom.compareTo(dateTo) == 0) {
                
                  System.out.println("From Date is Equal to To Date");
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}
Posted by: Guest on October-03-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language