简体   繁体   中英

Compare 24hr Strings with Java

I have the following String representation of 24hr like 1423 and 1956

I would like to check if the current time (with time zone) is between this pair

my current solution gets the hour and minute of the day using

int h = Instant.now().atZone(ZoneId.systemDefault()).getHour()
int t = Instant.now().atZone(ZoneId.systemDefault()).getMinute()

creating a 4 digit strings from the numbers, and do a string comparison

I don't like my solution at all, What's the elegant way to do it?

You can convert String representation of time to LocalTime as follows:

var formatter = DateTimeFormatter.ofPattern("HHmm");
var lowerTime = LocalTime.parse("1423", formatter);
var upperTime = LocalTime.parse("1956", formatter);

Then you can use isAfter() / isBefore methods to check if it is in between:

var nowTime = LocalTime.now(ZoneId.systemDefault());
boolean inBetween = nowTime.isAfter(lowerTime) && nowTime.isBefore(upperTime);

Create a LocalTime object using the ZonedDateTime.now() reference and subsequent call to ZonedDateTime#toLocalTime. Then create a DateTimeFormatter object using the Pattern HHmm which stands for hours (HH) and minutes (mm). Then you can create a LocalTime from the start time 1423 using the pattern, and an end time of 1956 from the pattern. You can then create a boolean representing whether or not your time is between by determining if the current time is after the start time and before the end time.

    LocalTime time = ZonedDateTime.now().toLocalTime();

    DateTimeFormatter pattern = DateTimeFormatter.ofPattern("HHmm");

    LocalTime startTime = LocalTime.parse("1423", pattern);

    LocalTime endTime = LocalTime.parse("1956", pattern);

    boolean between = time.isAfter(startTime) && time.isBefore(endTime);

As you note in the question, your strings are in 24-hour time with leading zeros, so you can compare them as strings. Here is a more convenient way to convert the current time to a string in the required format:

String now = DateTimeFormatter.ofPattern("HHmm")
                              .withZone(ZoneId.systemDefault())
                              .format(Instant.now());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM