Reputation: 25
I am writing a project which handles card reading for door passing. The system must check if the swiped card has permission to a specific door at that specific time. For example, some cards do not have permission during weekends or outside working hours which are 8-20. How do I program such a thing with Joda-Time?
Right now I have:
//The code below that I have only checks for within a given date and time range.
DateTime start = new DateTime(2012, 1, 1, 0, 0);
DateTime end = new DateTime(2012, 12, 31, 0, 0);
Interval interval = new Interval(start, end);
boolean DateTimeCheck3 = interval.contains(time); // time is predeclared and gets current time from another class
Upvotes: 2
Views: 1328
Reputation: 79085
java.time
In March 2014, Java 8 introduced the modern, java.time
date-time API which supplanted the error-prone legacy, java.util
date-time API. Also, shown below is a notice on the Joda-Time Home Page:
Note that from Java SE 8 onwards, users are asked to migrate to
java.time
(JSR-310) - a core part of the JDK which replaces this project.
LocalDateTime#getDayOfWeek
returns you an enum
constant for a given LocalDateTime
which you can use for your comparison. The advantage of representing the days of a week by enum constants rather than a number is that you no longer need to remember whether they start from 0 or 1.
Demo:
public class Main {
public static void main(String[] args) {
// A sample date-time corresponding to `time` in code of your question.
// ZoneId.systemDefault() gives you the ZoneId set to the JVM executing the code
// Replace it as per your requirement e.g. ZoneId.of("Europe/Stockholm").
LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
DayOfWeek dow = ldt.getDayOfWeek();
LocalTime time = ldt.toLocalTime();
if (dow == DayOfWeek.SATURDAY
|| dow == DayOfWeek.SUNDAY
|| time.isBefore(LocalTime.of(8, 0))
|| time.isAfter(LocalTime.of(20, 0))) {
System.out.println("Not allowed");
// Rest of the processing
} else {
System.out.println("Allowed");
// Rest of the processing
}
}
}
Note: As mentioned in this comment, LocalDateTime.now()
will give you the date-time in your JVM's time zone. For date-time in a specific time zone, pass an explicit time zone e.g., LocalDateTime.now(ZoneId.of("Europe/Stockholm"))
. One should consider using the richer ZonedDateTime
instead of LocalDateTime
.
Learn more about the modern Date-Time API from Trail: Date Time.
Upvotes: 2
Reputation: 17769
Using 1 <= time.getDayOfWeek() && time.getDayOfWeek() <= 5
You can ensure that the day of the week is between Monday 1
and Friday 5
.
Upvotes: 2