在java中根据时间显示早上、下午、晚上、晚上的消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27589701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Showing Morning, afternoon, evening, night message based on Time in java
提问by Devrath
What i am trying to do::
我正在尝试做什么::
Show message based on
显示消息基于
- Good morning (12am-12pm)
- Good after noon (12pm -4pm)
- Good evening (4pm to 9pm)
- Good night ( 9pm to 6am)
- 早上好(12am-12pm)
- 中午之后好(12pm -4pm)
- 晚上好(下午 4 点至晚上 9 点)
- 晚安(晚上 9 点至早上 6 点)
CODE::
代码::
I used 24-hr format to get this logic
我使用 24 小时格式来获取此逻辑
private void getTimeFromAndroid() {
Date dt = new Date();
int hours = dt.getHours();
int min = dt.getMinutes();
if(hours>=1 || hours<=12){
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(hours>=12 || hours<=16){
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(hours>=16 || hours<=21){
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(hours>=21 || hours<=24){
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}
}
Question:
题:
- Is this this best way of doing it, If no which is the best way
- 这是最好的方法吗,如果不是,这是最好的方法
采纳答案by SMA
You should be doing something like:
你应该做这样的事情:
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if(timeOfDay >= 0 && timeOfDay < 12){
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 12 && timeOfDay < 16){
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 16 && timeOfDay < 21){
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 21 && timeOfDay < 24){
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}
回答by Konstantin Yovkov
I would shorten your if/elseif
statement to:
我会将您的if/elseif
陈述缩短为:
String greeting = null;
if(hours>=1 && hours<=12){
greeting = "Good Morning";
} else if(hours>=12 && hours<=16){
greeting = "Good Afternoon";
} else if(hours>=16 && hours<=21){
greeting = "Good Evening";
} else if(hours>=21 && hours<=24){
greeting = "Good Night";
}
Toast.makeText(this, greeting, Toast.LENGTH_SHORT).show();
回答by user987339
You determine if it is in the first interval, and then all other intervals depends on the upper limit. So you can make it even shorter:
您确定它是否在第一个区间,然后所有其他区间取决于上限。所以你可以让它更短:
String greeting = null;
if(hours>=1 && hours<=11){
greeting = "Good Morning";
} else if(hours<=15){
greeting = "Good Afternoon";
} else if(hours<=20){
greeting = "Good Evening";
} else if(hours<=24){
greeting = "Good Night";
}
Toast.makeText(this, greeting, Toast.LENGTH_SHORT).show();
回答by m2k_72
try this code(get hours and get minute methods in Date class are deprecated.)
试试这个代码(不推荐使用 Date 类中的 get hours 和 get minute 方法。)
private void getTimeFromAndroid() {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
int hours = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
if(hours>=1 && hours<=12){
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(hours>=12 && hours<=16){
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(hours>=16 && hours<=21){
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(hours>=21 && hours<=24){
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}
}
回答by SREE
When I write
当我写
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
I didn't get output and it doesn't show any error. Just the timeOfDay
won't get assigned any value in the code. I felt it was because of some threading while Calendar.getInstance()
is executed. But when I collapsed the lines it worked for me. See the following code:
我没有得到输出,也没有显示任何错误。只是timeOfDay
不会在代码中分配任何值。我觉得这是因为在Calendar.getInstance()
执行时进行了一些线程处理。但是当我折叠线路时,它对我有用。请参阅以下代码:
int timeOfDay = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if(timeOfDay >= 0 && timeOfDay < 12){
greeting.setText("Good Morning");
}else if(timeOfDay >= 12 && timeOfDay < 16){
greeting.setText("Good Afternoon");
}else if(timeOfDay >= 16 && timeOfDay < 21){
greeting.setText("Good Evening");
}else if(timeOfDay >= 21 && timeOfDay < 24){
greeting.setText("Good Morning");
}
回答by Yoshua Nahar
java.time
时间
I would advise to use Java 8 LocalTime.
我建议使用 Java 8 LocalTime。
Maybe create a class like this to handle your time of day problem.
也许创建一个这样的类来处理您一天中的时间问题。
public class GreetingMaker { // think of a better name then this.
private static final LocalTime MORNING = LocalTime.of(0, 0, 0);
private static final LocalTime AFTER_NOON = LocalTime.of(12, 0, 0);
private static final LocalTime EVENING = LocalTime.of(16, 0, 0);
private static final LocalTime NIGHT = LocalTime.of(21, 0, 0);
private LocalTime now;
public GreetingMaker(LocalTime now) {
this.now = now;
}
public void printTimeOfDay() { // or return String in your case
if (between(MORNING, AFTER_NOON)) {
System.out.println("Good Morning");
} else if (between(AFTER_NOON, EVENING)) {
System.out.println("Good Afternoon");
} else if (between(EVENING, NIGHT)) {
System.out.println("Good Evening");
} else {
System.out.println("Good Night");
}
}
private boolean between(LocalTime start, LocalTime end) {
return (!now.isBefore(start)) && now.isBefore(end);
}
}
回答by Meno Hochschild
Using Time4J(or Time4A on Android) enables following solutions which do not need any if-else-statements:
使用Time4J(或 Android 上的 Time4A)可以启用以下不需要任何 if-else 语句的解决方案:
ChronoFormatter<PlainTime> parser =
ChronoFormatter.ofTimePattern("hh:mm a", PatternType.CLDR, Locale.ENGLISH);
PlainTime time = parser.parse("10:05 AM");
Map<PlainTime, String> table = new HashMap<>();
table.put(PlainTime.of(1), "Good Morning");
table.put(PlainTime.of(12), "Good Afternoon");
table.put(PlainTime.of(16), "Good Evening");
table.put(PlainTime.of(21), "Good Night");
ChronoFormatter<PlainTime> customPrinter=
ChronoFormatter
.setUp(PlainTime.axis(), Locale.ENGLISH)
.addDayPeriod(table)
.build();
System.out.println(customPrinter.format(time)); // Good Morning
There is also another pattern-based way to let the locale decide in a standard way based on CLDR-data how to format the clock time:
还有另一种基于模式的方法可以让语言环境根据 CLDR 数据以标准方式决定如何格式化时钟时间:
ChronoFormatter<PlainTime> parser =
ChronoFormatter.ofTimePattern("hh:mm a", PatternType.CLDR, Locale.ENGLISH);
PlainTime time = parser.parse("10:05 AM");
ChronoFormatter<PlainTime> printer1 =
ChronoFormatter.ofTimePattern("hh:mm B", PatternType.CLDR, Locale.ENGLISH);
System.out.println(printer1.format(time)); // 10:05 in the morning
ChronoFormatter<PlainTime> printer2 =
ChronoFormatter.ofTimePattern("B", PatternType.CLDR, Locale.ENGLISH)
.with(Attributes.OUTPUT_CONTEXT, OutputContext.STANDALONE);
System.out.println(printer2.format(time)); // morning
The only other library known to me which can also do this (but in an awkward way) is ICU4J.
我所知道的唯一可以做到这一点的其他图书馆(但以一种尴尬的方式)是 ICU4J。
回答by Sanjay Hadiya
private String getStringFromMilli(long millis) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(millis);
int hours = c.get(Calendar.HOUR_OF_DAY);
if(hours >= 1 && hours <= 12){
return "MORNING";
}else if(hours >= 12 && hours <= 16){
return "AFTERNOON";
}else if(hours >= 16 && hours <= 21){
return "EVENING";
}else if(hours >= 21 && hours <= 24){
return "NIGHT";
}
return null;
}
回答by Vishal Sonawane
For anyone who is looking for the latest Kotlinsyntax for @SMA's answer, here is the helper function :
对于正在为@SMA的答案寻找最新Kotlin语法的任何人,这里是辅助函数:
fun getGreetingMessage():String{
val c = Calendar.getInstance()
val timeOfDay = c.get(Calendar.HOUR_OF_DAY)
return when (timeOfDay) {
in 0..11 -> "Good Morning"
in 12..15 -> "Good Afternoon"
in 16..20 -> "Good Evening"
in 21..23 -> "Good Night"
else -> "Hello"
}
}
回答by awaik
If somebody looking the same for Dart and Flutter: the code without if statements - easy to read and edit.
如果有人对 Dart 和 Flutter 有相同的看法:没有 if 语句的代码 - 易于阅读和编辑。
main() {
int hourValue = DateTime.now().hour;
print(checkDayPeriod(hourValue));
}
String checkDayPeriod(int hour) {
int _res = 21;
Map<int, String> dayPeriods = {
0: 'Good night',
12: 'Good morning',
16: 'Good afternoon',
21: 'Good evening',
};
dayPeriods.forEach(
(key, value) {
if (hour < key && key <= _res) _res = key;
},
);
return dayPeriods[_res];
}