Answers for "compare two date"

1

date difference

function daysBetween(first, second) {

    // Copy date parts of the timestamps, discarding the time parts.
    var one = new Date(first.getFullYear(), first.getMonth(), first.getDate());
    var two = new Date(second.getFullYear(), second.getMonth(), second.getDate());

    // Do the math.
    var millisecondsPerDay = 1000 * 60 * 60 * 24;
    var millisBetween = two.getTime() - one.getTime();
    var days = millisBetween / millisecondsPerDay;

    // Round down.
    return Math.floor(days);
  
  // it will return date difference in days 
}
Posted by: Guest on February-03-2021
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