Answers for "java compare dates"

3

java compare dates

Date has before and after methods and can be compared to each other as follows:

if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
    // In between
}
For an inclusive comparison:

if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
    /* historyDate <= todayDate <= futureDate */ 
}
You could also give Joda-Time a go, but note that:

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

Back-ports are available for Java 6 and 7 as well as Android.
Posted by: Guest on March-11-2021
1

compare time in java

for ( Map.Entry<DayOfWeek , LocalTime> entry : dayToTimeMap.entrySet () ) {
    DayOfWeek key = entry.getKey ();
    LocalTime value = entry.getValue ();
    int comparison = key.compareTo ( today );
    if ( comparison < 0 ) { // if earlier day…
        earlier.add ( key );
    } else if ( comparison == 0 ) { //If same day…
        if ( value.isBefore ( now ) ) {
            earlier.add ( key );
        } else {  // Else same time as now or later than now…
            later.add ( key );
        }
    } else if ( comparison > 0 ) {
        later.add ( key );
    } else {
        throw new RuntimeException ( "Unexpectedly reached IF-ELSE for comparison: " + comparison );
    }
}
Posted by: Guest on June-07-2021
0

How to compare two string dates with different date formats in Java

package javaapplication;

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

public class date {

    public static void main(String[] args) {

        String startDate = "21-08-2027";
        String endDate = "21/08/2021";

        try {

            Date dateStart = new SimpleDateFormat("dd-MM-yyyy").parse(startDate);

            Date dateEnd = new SimpleDateFormat("dd/MM/yyyy").parse(endDate);

            if (dateStart.after(dateEnd)) {
                System.out.println("Start Date is greater than End Date");

            } else if (dateStart.before(dateEnd)) {

                System.out.println("Start Date is less than End Date");

            } else {

                System.out.println("Start Date is Equal to End 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