dam1ne
dam1ne

Reputation: 361

Get current time and check if time has passed a certain period

this code below gets the current time and timezone of the area

    Date date = new Date();
    DateFormat df = new SimpleDateFormat("HH:mm:ss");

    df.setTimeZone(TimeZone.getDefault());

    System.out.println("Time: " + df.format(date)); 

right now its 1:01 pm (at the time of typing)

what i need help doing is implementing a feature in the code that checks if the current time has passed, for example 1:00PM

but I have no idea where to even start, can you help me out?

Upvotes: 0

Views: 3345

Answers (2)

infinity8-room
infinity8-room

Reputation: 106

I see it has already answered with Time, but as a teaching point, if you really wanted to use Date, you could have done something like this:

public static void main(String[] args) {
    Date date = new Date();
    DateFormat df = new SimpleDateFormat("HH:mm:ss");
    df.setTimeZone(TimeZone.getDefault());
    System.out.println("Time: " + df.format(date));

    //If you print the date you'll see how it is formatted
    //System.out.println(date.toString());

    //So you can just split the string and use the segment you want
    String[] fullDate = date.toString().split(" ");

    String compareAgainstTime = "01:00PM";

    System.out.println(isPastTime(fullDate[3],compareAgainstTime));
    }

public static boolean isPastTime(String currentTime, String comparedTime) {
    //We need to make the comparison time into the same format as the current time: 24H instead of 12H:
    //then we'll just convert the time into only minutes to that we can more easily compare;
    int comparedHour = comparedTime[-2].equals("AM") ? String.valueOf(comparedTime[0:2]) : String.valueOf(comparedTime[0:2] + 12 );
    int comparedMin = String.valueOf(comparedTime[3:5]);
    int comparedT = comparedHour*60 + comparedMin;

    //obviously currentTime is alredy the correct format; just need to convert to minutes
    int currentHour = String.valueOf(currentTime[0:2]);
    int currentMin = String.valueOf(currentTime[3:5]);
    int currentT = currentHour*60 + currentMin;

    return (currentT > comparedT);
}

It's a bit messier, having to muddy into the Strings and whatnot, but it is possible. You would also have to be careful the zero-pad the comparedTime or just check for that in the function

Upvotes: 1

Andreas
Andreas

Reputation: 159135

Use the Java 8+ Time API class LocalTime:

LocalTime refTime = LocalTime.of(13, 0); // 1:00 PM
// Check if now > refTime, in default time zone
LocalTime now = LocalTime.now();
if (now.isAfter(refTime)) {
    // passed
}
// Check if now >= refTime, in pacific time zone
LocalTime now = LocalTime.now(ZoneId.of("America/Los_Angeles"))
if (now.compareTo(refTime) >= 0) {
    // passed
}

Upvotes: 5

Related Questions