I'm creating an app for a coffee shop which should display information about whether it is closed or open in a given time. The app should display either "OPEN" or "CLOSED" as a TextView
based on the time on user's device.
The coffee shop is open from 10:00:00 at morning and closed at 24:00:00 at night. Also, it is open from WED-SUN (MON and TUE closed).
For that, I created a TextView
layout in XML with empty text field:
<TextView
android:id="@+id/status_text_view"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
In java file I created a TextView
element and referred to the TextView
layout in the XML
file:
TextView textView = (TextView) findViewById(R.id.status_text_view);
I also fetched date and time from user's device by using:
String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());
From here I don't know how to do the final task of displaying either "OPEN" or "CLOSED" in the TextView
layout based on date,time and day on the user's device. What I could do is only display the current date and time in the TextView
layout by using the code:
textView.setText(currentDateTimeString);
Note : If you share any code, kindly add comments describing each line of code as I'm a beginner level programmer.
Java 8 introduces the java.time.*
package which should be prefered! You can find more information in Java SE 8 Date and Time
You should consider using java.time.LocalDateTime
.
The following function gives a simple example to decide if your shop is open:
import java.time.DayOfWeek;
import java.time.LocalDateTime;
boolean isOpen() {
LocalDateTime now = LocalDateTime.now();
// now.getHour/( returns the hour-of-day, from 0 to 23
// so every hour that is greater equals 10 means open
boolean isOpenByTime = now.getHour() >= 10;
DayOfWeek dayOfWeek = now.getDayOfWeek();
boolean isOpenByWeekDay = dayOfWeek != DayOfWeek.MONDAY && dayOfWeek != DayOfWeek.TUESDAY;
return isOpenByTime && isOpenByWeekDay;
}
You can then use isOpen()
like:
if(isOpen()) { textView.setText("OPEN"); } else { textView.setText("CLOSED"); }
Documentation