-8

I need to compare the time part from 2 date/time variables to see if the time is inbetween the current time in android. How can I do that?

    Boolean InBetweenTime(Date currentTime, Date StartTime, Date EndTime)
{
    Boolean result = false;
    Calendar calendar = Calendar.getInstance();
    if ((!currentTime.before(StartTime))&&(!currentTime.after(EndTime))){
        //between time
    } else {
        //not inbetween time
    }
    return result;
}
MTplus
  • 2,077
  • 4
  • 34
  • 51
  • 2
    Show what you've already tried – CodeMatrix Oct 22 '18 at 13:07
  • Explain better your problem please. – A. Wolf Oct 22 '18 at 13:08
  • 5
    You asked a [question](https://stackoverflow.com/questions/52929034/convert-only-time-part-in-android-from-string-to-time/52929217#52929217) earlier with no attempt, got your answer, and now you're asking your next question with no attempt. Please provide a [mcve] this time, and show your own attempt! Plus I gave you an example of how to compare times on your earlier question... – achAmháin Oct 22 '18 at 13:10
  • From https://stackoverflow.com/questions/52929034/convert-only-time-part-in-android-from-string-to-time to this – forpas Oct 22 '18 at 13:10
  • If you want to check if a date is in a range of 2 other dates, try [this](https://stackoverflow.com/questions/494180/java-how-do-i-check-if-a-date-is-within-a-certain-range). – A. Wolf Oct 22 '18 at 13:11
  • 2
    Read the javadocs of [`LocalDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html), [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) and [`LocalTime`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html) and maybe some examples, there are a lot of them in the www... – deHaar Oct 22 '18 at 13:14
  • I have this so far... – MTplus Oct 22 '18 at 13:15
  • Boolean InBetweenTime(Date currentTime, Date StartTime, Date EndTime) { Boolean result = false; Calendar calendar = Calendar.getInstance(); if ((currentTime.before(StartTime))&&(currentTime.after(EndTime))){ //time is inbetween } else { //time is not inbetween } return result; } – MTplus Oct 22 '18 at 13:15
  • I recommend you learn to use java.time, the modern Java date and time API. [Tutorial link](https://docs.oracle.com/javase/tutorial/datetime/). To use it on not-new Android, add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your project. – Ole V.V. Oct 22 '18 at 13:26
  • Assuming that start time is before end time, for current time to be between them it needs to be *after start* time and *before end* time, not the other way around. – Ole V.V. Oct 22 '18 at 13:29
  • I'm trying to stick to API level 15 for compability reasons and cannot use LocalTime, the above code would work if I only could compare the time part instead of the whole date/time. – MTplus Oct 22 '18 at 13:53
  • Though I have not got the experience I strongly believe that [the ThreeTenABP library that I already linked to once](https://github.com/JakeWharton/ThreeTenABP) is all you need to use `LocalTime` on API level 15. – Ole V.V. Oct 22 '18 at 17:09

3 Answers3

0

If what you need is to compare only time, ignoring date, then you should do something like this, so your 'date' part be equal in all three variables.

Boolean InBetweenTime(Date currentTime, Date startTime, Date endTime){
    Boolean result = false;

    //calendar for currentTime
    Calendar currentCal = Calendar.getInstance();
    currentCal.setTime(currentTime);
    //calendar for startTime
    Calendar startCal = Calendar.getInstance();
    startCal.setTime(startTime);
    //calendar for endTime
    Calendar endCal = Calendar.getInstance();
    endCal.setTime(endTime);
    //set corresponding date fields of startTime and endTime to be equal t ocurrentTime, so you compare only time fields
    startCal.set(currentCal.get(Calendar.YEAR), currentCal.get(Calendar.MONTH), currentCal.get(Calendar.DAY_OF_MONTH));
    endCal.set(currentCal.get(Calendar.YEAR), currentCal.get(Calendar.MONTH), currentCal.get(Calendar.DAY_OF_MONTH));
    //return true if between, false otherwise
    return (!currentTime.before(startCal.getTime())) && (!currentTime.after(endCal.getTime()));
}
0

To get the time part of a Date (which is a date/time value), use this:

Date date = ...
Instant instant = d.toInstant();
Instant midnight = instant.truncatedTo(ChronoUnit.DAYS);
Duration timeSinceMidnight = Duration.between(midnight, instant);
System.out.println(timeSinceMidnight);
Queeg
  • 7,748
  • 1
  • 16
  • 42
  • This gives us midnight in UTC. Most will want midnight in their own time zone. Also it's not so straightforward to compare `Duration` objects, which was wanted in rhe question. Better to get a `LocalTime`. But good that you are using java.time, the modern Java date and time API. – Ole V.V. Dec 01 '22 at 06:02
0

Solution using java.time API (Java 8+)

The solution would be clean and clear using the modern date-time API.

Demo:

import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        // Tests
        System.out.println(isBetween(Instant.parse("2022-11-20T20:30:00Z"), Instant.parse("2022-11-15T23:45:00Z")));
        System.out.println(isBetween(Instant.parse("2022-11-20T10:20:30Z"), Instant.parse("2022-11-15T20:10:05Z")));
        System.out.println(isBetween(Instant.parse("2022-11-20T10:20:30Z"), Instant.parse("2022-11-15T10:20:30Z")));
    }

    static boolean isBetween(Instant startInstant, Instant endInstant) {
        LocalTime currentTime = getTime(Instant.now());
        LocalTime startTime = getTime(startInstant);
        LocalTime endTime = getTime(endInstant);
        return currentTime.isAfter(startTime) && currentTime.isBefore(endTime);
    }

    static LocalTime getTime(Instant instant) {
        return instant.atZone(ZoneId.systemDefault()).toLocalTime();
    }
}

Output when I ran it at ~ 2022-11-30T23:32:00Z:

true
false
false

Learn more about the modern Date-Time API from Trail: Date Time.

Solution using Java version < 8

If your project is open to using 3rd party library for date-time, I recommend you check How to use ThreeTenABP in Android Project. The ThreeTenABP library makes it possible to backport java.time API to Java 6 and 7.

If you want to stick to the standard library of Java version < 8, here is a solution:

The trick is to set today's year, month and day into the startDate and endDate and then you can compare them as usual. If you have year, month and day the same across all three instances of Date, basically you comparing just their times.

Demo:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Main {
    public static void main(String[] args) throws ParseException {
        // Tests
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println(isBetween(sdf.parse("2022-11-20T20:30:00Z"), sdf.parse("2022-11-15T23:45:00Z")));
        System.out.println(isBetween(sdf.parse("2022-11-20T10:20:30Z"), sdf.parse("2022-11-15T20:10:05Z")));
        System.out.println(isBetween(sdf.parse("2022-11-20T10:20:30Z"), sdf.parse("2022-11-15T10:20:30Z")));
    }

    static boolean isBetween(Date startTime, Date endTime) {
        Date currentTime = new Date();
        // System.out.println(currentTime);
        Calendar currentCal = Calendar.getInstance();
        currentCal.setTime(currentTime);
        int year = currentCal.get(Calendar.YEAR);
        int month = currentCal.get(Calendar.MONTH);
        int day = currentCal.get(Calendar.DAY_OF_MONTH);

        // Set today's year, month and day into the startDate
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(startTime);
        startCal.set(year, month, day);
        startTime = startCal.getTime();
        // System.out.println(startTime);

        // Set today's year, month and day into the endDate
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(endTime);
        endCal.set(year, month, day);
        endTime = endCal.getTime();
        // System.out.println(endTime);

        return currentTime.after(startTime) && currentTime.before(endTime);
    }
}

Output when I ran it at ~ 2022-11-30T23:33:00Z:

true
false
false
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110