Problem description:
In my application the quiz stops when the date is not yet but the time is due but on a different date.
Example:
If I set date to August/20/2022
and endTime
to 11:00pm
, then the quiz stops on 19th August
when the time is 11:00pm
.
My code:
if (!(endTime.isBefore(now) && !(endDate.isBefore(LocalDate.now())))) {
out.print("more time");
} else {
stopdao.stopquiz();
}
CodePudding user response:
Firstly, don't use classes LocalDate
, LocalTime
and LocalDateTime
for server-side programming because they are not meant to represent a particular moment in time. They have a meaning only in the context of a particular Local
.
For the same moment in time, LocalDateTime
may vary in the range up 26-27
hours in different time zones.
Instead, you can use Instant
, which represents a point in time in UTC.
Secondly, you've messed around with your condition.
Let's assume that endTime
is of type Instant
. Then all that you need is the following:
Instant now = Instant.now();
if (now.isBefore(endTime)) {
out.print("more time");
} else {
stopdao.stopquiz();
}
CodePudding user response:
First of all - Consider thinking about more concious use of boolean logic. This code doesn't look understandable due to negation which can be replaced with equivalent OR expression. If your code compiles then I presume, a dollar mark is just a mistake in typing here and is normally a closing brace ")" which is missing.
Remember that Java estimates only the necessary part of conditions. Once the evaluation can't change it's value it is fixed and nothing else is being checked. (first meet false in && expression or first true in or expression) So if you check on the first place an hour in an AND expression the date will be checked ONLY in case the hour did not set the evaluation result.
Also if you use LocalDate/Time, why using negation in your logic instead simply use (time/date).isAfter()?
I'm not posting you the code - try fixing it yourself taking under consideration above mentioned things :)