-4

I have a date: actDate, and its time was extracted as string timeFromAct

Then I have a reference time from database: timeValue, this was converted to string as timeFromDB

DateFormat formatTime;
formatTime = new SimpleDateFormat("HH:mm:ss");  
Date actDate = actinfo.getActDate();
String timeFromAct = formatDay.format(actDate);

String date= ListOfConstants.SOME_DATE_REF;
ResultTable[] timeValue = RTManager.getSomethingDecodeList(date);
String timeFromDB = Arrays.toString(timeValue);

I know converting the two as Strings won't let me compare the 2 times but

I would like to know how do I compare these time values in an if statement (similar to below comparison)?

if (timeFromAct is greater than or equal to timeFromDB){
*some codes*
}
dcdum2018
  • 93
  • 1
  • 9
  • `actDate.before(timeFromDB)` or `actDate.compareTo(timeFromDB)` – chaos Sep 04 '18 at 10:00
  • 1
    if both strings are in the `HH:mm:ss` format they can be compared by the `compareTo` method of `String` (if you really need to compare as text). I would prefer to transform that strings to `LocalTime` (or so) and then compare using theirs `compareTo` – user85421 Sep 04 '18 at 10:02
  • 1
    @weaver I do not believe that `Date` has a `compareTo(String)` method – user85421 Sep 04 '18 at 10:03
  • 1
    @CarlosHeuberger see this. Date has compareTo function [Date javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) – drowny Sep 04 '18 at 10:07
  • 1
    I recommend you avoid the `SimpleDateFormat` and `DateFormat` classes. They are not only long outdated along with `Date`, they are 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/). – Ole V.V. Sep 04 '18 at 10:27
  • Using `LocalTime` from java.time is a good idea, @CarlosHeuberger. Simpler and clearer than `compareTo`, use its `isBefore` method. Use “not before” to mean “same time or after”. – Ole V.V. Sep 04 '18 at 10:30
  • What are the capabilities of your `ResultTable` class? What does `timeFromDB` look like exactly? Asking because I suspect that there’s an easier way than converting to string and back. – Ole V.V. Sep 04 '18 at 10:35
  • hi @OleV.V., unfortunately i cannot import java.time from where i'm doing the codes. ResultTable gets the value of time (HH:mm:ss) from database. – dcdum2018 Sep 04 '18 at 10:39
  • So `Arrays.toString(timeValue)` might give you `[]` or `[23:32:45]` or `[09:36:29, 11:12:12]` depending on the length of the array? What would be the desired result in each case? – Ole V.V. Sep 04 '18 at 10:42
  • What’s your Java version? java.time is built in from Java 8 and on. To use it with Java 6 or 7 you will need [the ThreeTen Backport library](https://www.threeten.org/threetenbp/), and import `org.threeten.bp.LocalTime` and froends. – Ole V.V. Sep 04 '18 at 10:45
  • it will surely return only 1 value like this: [23:32:45]. @OleV.V. – dcdum2018 Sep 04 '18 at 10:47
  • 1
    @drowny and by that documentation (and also by the Java 10 version of it) its argument is **not** a `String` ,is it? I definitively put that in my comment and `timeFromDB`, as suggested by @weaver, happens to be a `String` (part of the question) – user85421 Sep 04 '18 at 11:52
  • @CarlosHeuberger In Date library compareTo gives date to compare.In question both dates are String and same format like HH:mm:ss , questioner said. – drowny Sep 04 '18 at 11:53
  • @drowny OK, but `actDate` as used by @weaver is a `Date`, not a `String`. And **you** posted the link to the method of the `Date` class... – user85421 Sep 04 '18 at 11:55
  • yes @weaver used as Date. But in question both are String , so i provided to compare these string with compareTo which is using in String library. I posted 2 solution, one of them is with Date comparasion and other one related as String comparasion usage. – drowny Sep 04 '18 at 11:59
  • @drowny I was meaning your reply: "@CarlosHeuberger see this. Date has compareTo function Date javadoc", to my comment: "@weaver I do not believe that Date has a compareTo(String) method" (I am **not** commenting your answer, this is the questions section) – user85421 Sep 04 '18 at 12:12

2 Answers2

1

Write like this ;

if (actDate.after(timeFromDb) || actDate.compareTo(timeFromDB)==0 ){
*some codes*
}

In detail

  • actDate.after(timeFromDb) provides greater than case.
  • actDate.compareTo(timeFromDB)==0 provides equality of actDate and timeFormDb.

Or in String comparasion if both are same format ;

if(timeFromAct.compareTo(timeFromDB) > 0 || timeFromAct .equals(timeFromDB)){..}

or more simple

if(!(timeFromAct.compareTo(timeFromDB) < 0)){..}

String.compareTo works as

"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns  0
"b".compareTo("a"); // returns a positive number, here 1
drowny
  • 2,067
  • 11
  • 19
  • hi @drowny, i have 2 time with same format but in string. `String timeFromAct = formatDay.format(actDate);` `String timeFromDB = Arrays.toString(timeValue);` Will this work if both time are in string? `if (timeFromAct.after(timeFromDb) || actDate.compareTo(timeFromDB)==0 )` – dcdum2018 Sep 04 '18 at 10:28
  • If both are in string, Do it directly like `if(timeFromAct > timeFromDB || timeFromAct .equals(timeFromDB)){..}` – drowny Sep 04 '18 at 10:33
  • i just tried but error occurred: `operator > cannot be applied to java.lang.String,java.lang.String` – dcdum2018 Sep 04 '18 at 10:35
  • Sory change with this `if(timeFromAct.compareTo(timeFromDB) > 0 || timeFromAct .equals(timeFromDB)){..}` . I updated the post – drowny Sep 04 '18 at 10:38
  • can you please explain the compareTo part? does it mean if i want `timeFromAct` < `timeFromDB`, i can simply write `(timeFromAct.compareTo(timeFromDB) < 0` ? – dcdum2018 Sep 04 '18 at 10:44
  • Yes i explained in my post. you can check. CompareTo makes a string comparasion. If timeFromAct smaller than timeFromDb , it returns negative number. If not returns positive number. if equal returns zero. and you can compare with it – drowny Sep 04 '18 at 10:49
  • thank you, @drowny. are the following correct? `21:59:59.compareTo(22:00:00) -> returns -1` `22:00:01.compareTo(22:00:00) -> returns 1` – dcdum2018 Sep 04 '18 at 11:05
  • of course true like your said. Your comparable statement should be zero. If return smaller than zero --> this is smaller. If return greater than zero --> this is greater. If returns zero. they are equal. – drowny Sep 04 '18 at 11:13
  • @dcdum2018 why do you not just test it? Java 10 has the very helpful command `jshell` - so you don't need to write a whole program to test just that commands You should write `"21:59:59".compareTo("22:00:00")`, that is, using quotes – user85421 Sep 04 '18 at 12:19
  • dit it worked correctly? i will try with java 10 thx @CarlosHeuberger – drowny Sep 04 '18 at 12:19
  • @drowny that comment was meant to "dcdum2018" - that's why I wrote `@dcdum2018` at the beginning - he should test it – user85421 Sep 04 '18 at 12:23
1

LocalTime from java.time

    Date actDate = actinfo.getActDate();
    ResultTable[] timeValue = RTManager.getSomethingDecodeList(date);

    LocalTime actualTime = actDate.toInstant()
            .atZone(ZoneId.systemDefault())
            .toLocalTime();
    if (timeValue.length == 1) {
        LocalTime timeFromDB = LocalTime.parse(timeValue[0].toString());
        if (! actualTime.isBefore(timeFromDB)) {
            System.out.println("timeFromAct is greater than or equal to timeFromDB");
        } else {
            System.out.println("timeFromAct is less than timeFromDB");
        }
    } else {
        System.out.println("Unexpected number of ResultTable entries: " + timeValue.length);
    }

A LocalTime is a time of day without date and without time zone. I believe that this is exactly what you need.

I have assumed that getActDate invariably returns an old-fashoined Date object. It would be better if you can modify it to return an appropriate type from java.time, the modern Java date and time API.

In the conversion from Date to LocalTime in the above code you will need to get your time zone right, or you will get incorrect results. I have tentatively assumed the JVM time zone setting, notated as ZoneId.systemDefault(), since the SimpleDateFormat in your question used this; but this is fragile since the setting can be changed from another part of your program or another program running in the same JVM. Better if you can specify the correct time zone like for example ZoneId.of("Asia/Manila").

Do check your assumptions. RTManager.getSomethingDecodeList will surely return only 1 value like this: [23:32:45]. The check costs so little, and it will be expensive to track down the bug if some day a new programmer on your project modifies it to return an array of a different length. Do help by issuing a helpful error message in this case.

The date-time classes that you used — DateFormat, SimpleDateFormat and Date — are long outdated and poorly designed. The first two in particular are renowned for being troublesome. I see no reason why you should want to use any of those if you can avoid it.

unfortunately i cannot import java.time from where i'm doing the codes.

If you are using at least Java 6, you can use java.time.

  • In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161