我正在构建一个应用程序,我需要知道如何比较两个小时。
例如:我的商店在06:30 am
营业,在17:00 pm
关闭,我需要在Textview中显示
17:00 pm
之后,我的商店关闭,06:00 am
之后,我的商店从星期一到星期五营业。
我该怎么做?
我遇到多个错误:
我在06:30加上“:”时打开一个int整数
两个星期一至星期五的限制
请在我的代码下面找到:
public void timer () {
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
int open = 6:30; // 1 ERROR HERE WITH ":"
int close = 17;
if(timeOfDay < close){
hour.setText.("OPEN");
}}
感谢您的帮助。
答案 0 :(得分:7)
您应该使用Java 8 Date&Time库,因为Calendar和Date已过时。
LocalTime
类应该足够。
LocalTime open = LocalTime.of(6, 30);
LocalTime closed = LocalTime.of(17, 0);
LocalTime currentTime = LocalTime.now();
if (currentTime.isBefore(open) || currentTime.isAfter(closed)) {
// Closed
}
然后您可以使用DateTimeFormatter
类将时间格式化为所需的格式。
如果您在确定商店的营业时间时也要考虑星期几,则可以将LocalDateTime
与上述示例结合使用:
LocalDateTime now = LocalDateTime.now();
// The opening days. Static import these from java.time.DayOfWeek
Set<DayOfWeek> daysOpen = new HashSet<>(Arrays.asList(
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY));
// Opening and closing times
LocalTime timeOpen = LocalTime.of(6, 30);
LocalTime timeClosed = LocalTime.of(17, 0);
if (!daysOpen.contains(now.getDayOfWeek()) || now.toLocalTime().isBefore(timeOpen) || now.toLocalTime().isAfter(timeClosed)) {
System.out.println("Closed");
}
else {
System.out.println("Open");
}
答案 1 :(得分:0)
常数HOUR_OF_DAY
是仅表示小时的整数。我建议使用方法getTime()
(see this link),然后使用返回的Date
对象。
答案 2 :(得分:0)
我想不出一种非常简洁的方法来做到这一点,但也许您可以使用此方法
public boolean isOpen(Calendar c) {
int minute = c.get(Calendar.MINUTE);
int hour = c.get(Calendar.HOUR_OF_DAY);
return (hour < 17 && (hour > 6 || (hour == 6 && minute >=30)));
}
如果它在6:30到17:00之间,则应返回true,在其他任何时间返回false
(如果小时小于17,并且 (小时大于6,或小时为6,分钟为30或更高))
答案 3 :(得分:-1)
HOUR_OF_DAY field
的工作原理是这样的。
10:04:15 PM the HOUR_OF_DAY is 22.
您不会得到6:30 am
,因为它只会告诉您什么时间而不是分钟。
您可以致电MINUTE
来获取通话记录。
一些更改是:
public void timer () {
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
int minuteOfHour = c.get(Calendar.MINUTE); -> same as Hour
int open = 6; -> you shouldn't use ':' with an int
int openMinutes = 30;
int close = 17;
if(timeOfDay >= open && minuteOfHour >= openMinutes && timeOfDay < close){
hour.setText.("OPEN");
}}
答案 4 :(得分:-1)
使用以下代码:
Calendar openingHour = Calendar.getInstance();
openingHour.set(Calendar.HOUR_OF_DAY, 6);
openingHour.set(Calendar.MINUTE, 30);
openingHour.set(Calendar.SECOND, 0);
openingHour.set(Calendar.MILLISECOND, 0);
Calendar closingHour = Calendar.getInstance();
closingHour.set(Calendar.HOUR_OF_DAY, 17);
closingHour.set(Calendar.MINUTE, 0);
closingHour.set(Calendar.SECOND, 0);
closingHour.set(Calendar.MILLISECOND, 0);
Calendar currentTime = Calendar.getInstance();
int dayOfWeek = currentTime.get(Calendar.DAY_OF_WEEK);
if( dayOfWeek % 7 > 1 && currentTime.before(closingHour) && currentTime.after(openingHour)){
System.out.println("Store is open");
} else {
System.out.println("Store is closed");
}