Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

java - How to display either of the two values as a TextView, based on the time and date on the user's device?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...