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

时间:2014-12-21 13:13:39

标签: java android date time

我想做什么::

根据

显示讯息
  • 早上好(上午12点至下午12点)
  • 中午(下午12点至下午4点)之后很好
  • 晚上好(下午4点到晚上9点)
  • 晚安(晚上9点至早上6点)

CODE ::

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

问题:

  • 这是这种做法的最佳方式,如果没有哪种方法是最好的方式

16 个答案:

答案 0 :(得分:60)

你应该做的事情如下:

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

答案 1 :(得分:5)

我会将您的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();

答案 2 :(得分:3)

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);
  }

}

答案 3 :(得分:2)

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

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();

答案 4 :(得分:2)

尝试此代码(不推荐使用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();
    }
}

答案 5 :(得分:2)

对于正在寻找最新的 Kotlin 语法作为@SMA答案的任何人,这是帮助函数:

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"
          }
      }
    }

答案 6 :(得分:1)

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

答案 7 :(得分:1)

 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;
}

答案 8 :(得分:0)

写作时

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");
}

答案 9 :(得分:0)

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

答案 10 :(得分:0)

using System;

namespace PF_Claas_Assign1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime Greeting = DateTime.Now;

            if (Greeting.Hour >= 5 && Greeting.Hour < 12)
            {
                Console.WriteLine("Good morning....!");
            }
            else if (Greeting.Hour >= 12 && Greeting.Hour < 16)
            {
                Console.WriteLine("Good afternoon...!");
            }
            else if (Greeting.Hour >= 16 && Greeting.Hour < 20)
            {
                Console.WriteLine("Good evening...!");
            }
            else
            {
                Console.WriteLine("Good night...!");
            }
        }
    }
}

答案 11 :(得分:0)

在Kotlin中使用以下

fun getCurrentTime(dateFormatInPut:String,myDate:String): Time {
        val sdf = SimpleDateFormat(dateFormatInPut, Locale.ENGLISH)
        val date = sdf.parse(myDate)
        val millis = date!!.time
        val calendar=Calendar.getInstance()
        calendar.timeInMillis=millis
        return when (calendar.get(Calendar.HOUR_OF_DAY)) {
            in 0..11 -> Time.Morning
            in 12..15 -> Time.AfterNoon
            else -> Time.Evening
        }

    }

这里是枚举类

enum class Time {
Morning,
AfterNoon,
Evening

}

答案 12 :(得分:0)

一种更清洁的日期检测方法将是

//the time cannot go below zero, so if this case is true, it must be between 0 and 12
   if(time <= 12)
   {
       return "Good Morning";
       //it will only fall into this case if the time is greater than 12.
   }else if(time < 16)
   {
       return "Good Afternoon";
   }else if(time < 21)
   {
       return "Good Evening";
   }else //it is guaranteed that the time will not exceed 24
       //, and if the previous case are all false, it must be within 21 and 24
   {
       return "Good Night";
   }

答案 13 :(得分:0)

您同样可以拥有一个返回问候语的类。

import java.util.Calendar;

public class Greetings {
    public static String getGreetings()
    {
        Calendar c = Calendar.getInstance();
        int timeOfDay = c.get(Calendar.HOUR_OF_DAY);

        if(timeOfDay < 12){
            return "Good morning";
        }else if(timeOfDay < 16){
            return "Good afternoon";
        }else if(timeOfDay < 21){
            return "Good evening";
        }else {
            return "Good night";
        }
    }
}

答案 14 :(得分:0)

对于Kotlin用户,他们可以像这样使用它:

private fun showDayMessage():String {
    val c: Calendar = Calendar.getInstance()
    var message:String ?=null
    val timeOfDay: Int = c.get(Calendar.HOUR_OF_DAY)
    if (timeOfDay >= 0 && timeOfDay < 12) {
        message =  "Good Morning"
    } else if (timeOfDay >= 12 && timeOfDay < 16) {
        message =  "Good Afternoon"
    } else if (timeOfDay >= 16 && timeOfDay < 21) {
        message =  "Good Evening"
    } else if (timeOfDay >= 21 && timeOfDay < 24) {
        message =  "Good Night"
    }
    return  message!!
}

答案 15 :(得分:-1)

更具体

public static String getDayMessage() {
    Calendar c = Calendar.getInstance();
    int timeOfDay = c.get(Calendar.HOUR_OF_DAY);

    if (timeOfDay < 5) {
        return "Hi, Good Mid Night";
    }else if (timeOfDay < 6) {
        return "Hi, Good Late Night";
    } else if (timeOfDay < 12) {
        return "Hi, Good Morning";
    } else if (timeOfDay < 14) {
        return "Hi, Good Noon";
    } else if (timeOfDay < 16) {
        return "Hi, Good Afternoon";
    } else if (timeOfDay < 21) {
        return "Hi, Good Evening";
    } else {
        return "Hi, Good Night";
    }
}