-3

I have two date time string, one is current time and second is given as follows.

String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";

Now I want to check if the endTime has passed currentTime.

Thanks

Paul Chu
  • 1,249
  • 3
  • 19
  • 27
Yasir Ameen
  • 65
  • 2
  • 9

3 Answers3

5

Take a look at this and this

Example:

String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyyHH:mm:ss");

try {
    Date currentTimeDate = sdf.parse("05/30/2018 16:56:21");
    Date endTimeDate = sdf.parse("05/30/2018 16:59:21");
    currentTimeDate.compareTo(endTimeDate); // false / current time has not passed end time.
    endTimeDate.compareTo(currentTimeDate); // true / end time has passed current time.
} catch (ParseException ignored) {

}
Paul Chu
  • 1,249
  • 3
  • 19
  • 27
2

Convert both strings to Date object and then use before() method to check if the end time has passed currentTime.

String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21"; 

    Date current=new SimpleDateFormat("dd/MM/yyyy").parse(currentTime);  
    Date end=new SimpleDateFormat("dd/MM/yyyy").parse(endTime); 

    if(end.before(current)) {
      // end time has passed currenctTime
    } else {
      // no
    }
Nakesh
  • 546
  • 2
  • 7
  • 8
2

Keep both times in milliseconds which is a long value

long currentTime= System.currentTimeMillis();

You can also convert your and time in millies using below code.

String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013"; 
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
    Date mDate = sdf.parse(givenDateString);
    long endTime= mDate.getTime();
    System.out.println("Date in milli :: " + endTime);
} catch (ParseException e) {
            e.printStackTrace();
}

Now compare, if current time is larger then end time, thus current time has passed end time like below.

if(currentTime>endTime){
//Do stuff
}

Enjoy..