在java中显示基于时间的早晨,下午,晚上,晚上的消息

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在java中显示基于时间的早晨,下午,晚上,晚上的消息相关的知识,希望对你有一定的参考价值。

我想做什么::

显示基于的消息

  • 早上好(上午12点至下午12点)
  • 中午后(中午12点至下午4点)好
  • 晚上好(下午4点到晚上9点)
  • 晚安(晚上9点至早上6点)

码::

我使用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();
        }
    }

题:

  • 这是最好的方式,如果没有这是最好的方式
答案

你应该做的事情如下:

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();
}
另一答案

如果有人对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];
}
另一答案

我会将你的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();
另一答案

对于正在为@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"
          }
      }
    }
另一答案

java.time

我建议使用Java 8 LocalTime。

也许创建一个这样的类来处理你的时间问题。

public class GreetingMaker { // think of a better name than 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);
  }

}
另一答案

您确定它是否在第一个间隔中,然后所有其他间隔取决于上限。所以你可以做得更短:

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();
另一答案

试试这段代码(不推荐使用Date类和获取Date类中的分钟方法。)

 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();
    }
}
另一答案

使用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

还有另一种基于模式的方法让区域设置基于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

我所知道的唯一一个也可以做到这一点的其他库(但是以一种尴尬的方式)是ICU4J。

另一答案
 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;
}
另一答案

当我写作

Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);

我没有得到输出,也没有显示任何错误。只是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");
}

以上是关于在java中显示基于时间的早晨,下午,晚上,晚上的消息的主要内容,如果未能解决你的问题,请参考以下文章

taotao--maven框架搭建思路(用时1下午+1晚上)

Oracle 查询排除周末和下午 6 点到晚上 9 点

VueJs判断时间是上午还是下午晚上

SQL BigQuery:选择基于时间的查询

一周规划汇总_2016-09-04

UVA11389 The Bus Driver Problem