-1

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 i.e 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");
    }
JeffC
  • 22,180
  • 5
  • 32
  • 55
Mani
  • 75
  • 2
  • 10
  • 1
    Parse them into java.util.Date. Then use .compareTo(). – bcr666 Oct 12 '18 at 11:45
  • https://www.tutorialspoint.com/java/util/calendar_before.htm https://www.tutorialspoint.com/java/util/date_before.htm – Infern0 Oct 12 '18 at 11:46
  • 1
    Possible duplicate of [How to compare dates in Java?](https://stackoverflow.com/questions/2592501/how-to-compare-dates-in-java) – JeffC Oct 12 '18 at 13:25
  • This has nothing to do with Selenium. – JeffC Oct 12 '18 at 13:26
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Oct 12 '18 at 18:35
  • I may be repeating what I and @BasilBourque have already said, but I find it important enough: I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Also despite their names neither `Date` nor `Calendar` represents a calendar date. – Ole V.V. Oct 12 '18 at 19:48

4 Answers4

2

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

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.

Jan S.
  • 994
  • 1
  • 9
  • 21
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Oct 12 '18 at 18:36
0

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.

steffen
  • 16,138
  • 4
  • 42
  • 81
  • 1
    `Instant` is not the right class here. The problem involves a date-only value (no time-of-day, no time zone), but `Instant` is a moment, a date with time-of-day in UTC. So not properly representative. Instead, use `LocalDate`. – Basil Bourque Oct 12 '18 at 18:37
  • Also when you can use java.time — which is a very good idea — mixing the outdated and troublesome `SimpleDateFormat` and friends in is just overcomplicating things. – Ole V.V. Oct 12 '18 at 19:54
0

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.

Ashish Kamble
  • 2,555
  • 3
  • 21
  • 29
  • 2
    Why are you mixing the modern *java.time* classes with the terrible legacy classes? As of JSR 310, the legacy classes are entirely supplanted, and need not ever be used at all. – Basil Bourque Oct 12 '18 at 18:38
  • @BasilBourque is right, this is really overcomplicating things. – Ole V.V. Oct 12 '18 at 19:51