显示上午,下午,傍晚,晚上在Java的基础上的时间信息基础上、傍晚、上午、下午

2023-09-06 07:33:32 作者:傾壹世.等壹人

根据显示信息

早上好(12 AM-12PM)中午(12点-4pm)后好晚上好(下午4点到晚上9点)晚安(晚上9点到早上6点)

我用24小时制得到这个逻辑

I used 24-hr format to get this logic

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