yumi
yumi

Reputation: 153

Fail to compare time ranges

I have two String variables:

time22 will get the most current time while the timeInTheList will store some previous time.

I would like to compare both of these two times whether it have passed 30 minutes or not but I can't make it happen.

I found out some weird data printed out for the date, time and year and I only need the time, I will not need any date or year.

Code:

 for(int x = 1;x<list1.size();x+=3)
   {
    try{
         System.out.println("The time grab by linux command :"+time22);
         String timeInTheList = list1.get(x);
         System.out.println("The time in the balcklist.txt :" +timeInTheList);
         SimpleDateFormat dateFormat1 = new SimpleDateFormat("HH:MM:SS"); 
         Date Ftime1 = dateFormat1.parse(timeInTheList);
         Date Stime2 = dateFormat1.parse(time22);
         System.out.println("The Ftime1 value is :" +Ftime1);
         System.out.println("The Stime2 value is :" +Stime2);
         long diff1 = Stime2.getTime() - Ftime1.getTime();
         System.out.println(Stime2.getTime());
         System.out.println(Ftime1.getTime());
         System.out.println("Difference between two time is :"+diff1);
         if(diff1 > 1800)
          {
            System.out.println("it is more than  30 minute in the list");
            String DeletedRule = list1.get(x+1).toString();
            FinalDeletion(DeletedRule);
          }
         else
          {
            System.out.println("Keep in the list first,still not reach 30 minute");
          }
        }
     catch(ParseException e)
       {
         e.printStackTrace();
       }
   }



This is the output from my program:

Time from linux command(In TimeIsNow Method) :22:02:50
The time grab by linux command :22:02:50
The time in the balcklist.txt :21:19:46
The Ftime1 value is :Thu Jul 01 21:00:00 MYT 1971
The Stime2 value is :Sun Feb 01 22:00:00 MYT 1970
2730600050
47223000046
Difference between two time is :-44492399996
Keep in the list first,still not reach 30 minute

Upvotes: 1

Views: 226

Answers (2)

user7605325
user7605325

Reputation:

In Joda-Time, you can use a DateTimeFormatter to parse the input String and create LocalTime objects - LocalTime seems to be the best option, as you're dealing only with time (hour/minute/second) and don't need to know the date (day/month/year).

Having the LocalTime objects, you can use the Minutes class to get the minutes between them:

import org.joda.time.LocalTime;
import org.joda.time.Minutes;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

String time22 = "22:02:50";
String timeInTheList = "21:19:46";

// create formatter with format hour:minute:second
DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");

// parse Strings
LocalTime sTime2 = fmt.parseLocalTime(time22);
LocalTime fTime1 = fmt.parseLocalTime(timeInTheList);

// get the minutes between them
int minutes = Minutes.minutesBetween(fTime1, sTime2).getMinutes();
System.out.println(minutes); // 43

The code above will output 43 (the number of minutes between 21:19:46 and 22:02:50).

As the inputs are in a standard ISO-8601 format (HH:mm:ss), you can also parse them without a formatter:

LocalTime sTime2 = LocalTime.parse(time22);
LocalTime fTime1 = LocalTime.parse(timeInTheList);

Java new Date/Time API

Joda-Time is being discontinued and replaced by the new APIs, so I don't recommend start a new project with joda. Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".

So, if you don't have a huge codebase in Joda-Time (which would require a lot of work to migrate) or if you want to use the new API's, check how to use it below.

The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and they're being replaced by the new APIs.

If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

The code below works for both. The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.

The code is very similar to Joda's:

// if you're using ThreeTen Backport, replace java.time by org.threeten.bp
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

String time22 = "22:02:50";
String timeInTheList = "21:19:46";

// parse Strings
LocalTime sTime2 = LocalTime.parse(time22);
LocalTime fTime1 = LocalTime.parse(timeInTheList);

// get the minutes between them
long minutes = ChronoUnit.MINUTES.between(fTime1, sTime2);
System.out.println(minutes); // 43

The output is the same (43 minutes).


Notes:

In your original code, there are 2 problems:

  • The format is wrong: MM is the month, and SS is the fraction of second (check SimpleDateFormat javadoc for more details). That's why you're getting unexpected results when parsing:
    • when parsing 22:02:50, it takes 02 as the month (so it becomes February). All the missing fields are set to default values (day is 1, year is 1970, minutes is 0 and so on)
    • when parsing 21:19:46, it takes 19 as the month. So the parser takes the default value for year (1970) and take the 19th month from it (considering that January of 1970 is the first month, the 19th month is July of 1971)
  • The getTime() method returns the number of milliseconds since January 1, 1970, 00:00:00 GMT, so you're getting the difference in milliseconds (you'd need to convert it to minutes).

Anyway, using Joda-Time (or the new Date/Time API) make things much easier and I don't recommend using the old SimpleDateFormat class.

Upvotes: 1

Keyur Panchal
Keyur Panchal

Reputation: 1402

If you are using Java 8, you can use New Date/Time API. Please try below code:

// Required imports
import java.time.LocalTime;
import java.time.Duration;

// Taken hard-coded values for testing purpose
String time22 = "22:02:50", timeInTheList = "21:19:46";

LocalTime Stime2 = LocalTime.parse(time22);
LocalTime Ftime1 = LocalTime.parse(timeInTheList);

System.out.println("Stime2: " + Stime2);
System.out.println("Ftime1: " + Ftime1);

Duration duration = Duration.between(Ftime1, Stime2);
long diff1 = duration.getSeconds();
System.out.println("duration: " + diff1);

if(diff1 > 1800){
  System.out.println("it is more than 30 minute in the list");
  /**
   * Your remaining code goes here.
   */
}else{
  System.out.println("Keep in the list first, still not reach 30 minute");
}

Upvotes: 2

Related Questions