简体   繁体   中英

Java how to do Calendar comparison

I am taking start date from one text and storing in one string variable. I want to compare that start date with the current date ie start date is earlier than the current date or not.

public static void main(String[] rags) throws ParseException{
    String total= "I am Going to join in scholl at 21/10/2108";
    String[] effectiveDateText=total.split(" ");
    String effectiveDate=effectiveDateText[effectiveDateText.length-1];
    System.out.println(effectiveDate);
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Calendar today = Calendar.getInstance();
    String todate=sdf.format(today.getTime());
    System.out.println(todate);
    if(effectiveDate<todate){
        System.out.println("effective date is less then the previous date");
    }

tl;dr

Use modern LocalDate class.

LocalDate.parse(                                       // Represent a date-only value without time-of-day and without time zone in `java.time.LocalDate` class.
        "I am Going to join in scholl at 21/10/2108".  // Split your input string, looking for last part separated by a SPACE.
        .substring( 
                "I am Going to join in scholl at 21/10/2108".lastIndexOf( " " ) 
                + 1                 
        ) 
        ,
        DateTimeFormatter.ofPattern( "dd/MM/uuuu" )    // Specify formatting pattern to match your input. Tip: Use ISO 8601 formats instead.
)
.toString()                                            // Generate text in standard ISO 8601 format.

2108-10-21

Splitting string

First split the string into pieces.

String input = "I am Going to join in scholl at 21/10/2108";
String[] parts = input.split( " " );

Look at those parts.

for ( String part : parts ) {
    System.out.println( part );
}

I

am

Going

to

join

in

scholl

at

21/10/2108

Extract the last part.

String part = parts[ parts.length - 1 ]; // Subtract 1 for index (annoying zero-based counting).

LocalDate

The modern approach uses the java.time classes. Specifically, LocalDate for a date-only value without time-of-day and without time zone or offset-from-UTC.

Parse that last part as a LocalDate . Define a formatting pattern to match.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( part , f );

ISO 8601

Whenever possible, do not exchange date-time values textually using formats intended for presentation to humans.

Instead, use formats defined for the purpose of data-interchange in the ISO 8601 standard. For a date-only value, that would be: YYYY-MM-DD

The java.time classes use the ISO 8601 formats by default when parsing/generating text.

String output = LocalDate.now().toString()

2018-01-23


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

You shoud parse your dates into the Date format and the use the provided methods like this:

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    Date date1 = sdf.parse("21/10/2108");
    Date date2 = sdf.parse("20/01/2018");

    System.out.println("date1 : " + sdf.format(date1));
    System.out.println("date2 : " + sdf.format(date2));

    // after
    if (date1.after(date2)) {

    }
    // before
    if (date1.before(date2)) {

    }

nice to know: You should be carefull if you what to use date1.equals(date2) since this works on milliseconds precision aswell so you have to use a date delta if you allow user to enter time values in the future.

A Java Instant has very useful methods to compare two instant with each other, namely isAfter() and isBefore() . See this example:

String total = "I am Going to join in scholl at 21/10/2018";
String[] effectiveDateText = total.split(" ");
String effectiveDate = effectiveDateText[effectiveDateText.length - 1];
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Instant joinDate = sdf.parse(effectiveDate).toInstant();
if (Instant.now().isAfter(joinDate)) {
    // ...
}

You should however consider timezones. For instance, at present time ( Instant.now() ), at most parts in the world, it's 12/10/2018, at some however, it's already 13/10/2018 (Samoa), and at others it's 11/10/2018 (the US Minor Outlying Islands, only one minute left).

BTW, I changed 21/10/2108 to 21/10/2018.

You can use this code for comparison,

LocalDate currentDate = LocalDateTime.now().toLocalDate();
String cDate = ""+currentTime.getMonth().toString()+"/"+currentTime.getDayOfMonth().toString()+"/"+currentTime.getYear().toString();

Now cDate will have date string in format of dd/MM/yyyy. So for comaparison you can use Date class,

Date dOne = new SimpleDateFormat("dd/MM/yyyy").parse(cDate);
Date dTwo = new SimpleDateFormat("dd/MM/yyyy").parse(effectiveDate);

then use compareTo() method on both the dates,

dOne.compareTo(dTwo); // check value of this method

This return 0 if both dates are same,
if less than 0 means Date is before the argument date,
if greater than 0 means Date is after the argument date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM