Android的日历得到一周的当前日期作为字符串字符串、日历、日期、Android

2023-09-06 07:45:20 作者:幸福?发送失败

我试图得到一个字符串与实际工作日的名字是这样的:

i tried to get a string with the name of the actual weekday this way:

            Calendar c = Calendar.getInstance();
            int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

            if (c.get(Calendar.MONDAY) == dayOfWeek) weekDay = "monday";
            else if (c.get(Calendar.TUESDAY) == dayOfWeek) weekDay = "tuesday";
            else if (c.get(Calendar.WEDNESDAY) == dayOfWeek) weekDay = "wednesday";
            else if (c.get(Calendar.THURSDAY) == dayOfWeek) weekDay = "thursday";
            else if (c.get(Calendar.FRIDAY) == dayOfWeek) weekDay = "friday";
            else if (c.get(Calendar.SATURDAY) == dayOfWeek) weekDay = "saturday";
            else if (c.get(Calendar.SUNDAY) == dayOfWeek) weekDay = "sunday";

平日停留总是空,我居然不知道为什么,因为调试说一周中的某天 5这样我应该等于 c.get(Calendar.THURSDAY)

but weekDay stays always null and i actually have no idea why because the debugger says that dayOfWeek is 5 so i should be equal to c.get(Calendar.THURSDAY)

推荐答案

我做做到了这一点如下:

I accomplished this by doing the following:

String weekDay;
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", Locale.US);

Calendar calendar = Calendar.getInstance();
weekDay = dayFormat.format(calendar.getTime());

使用天格式EEEE将返回完整星期名称,如周二 使用天格式E将返回缩写名称,即星期二 的另一个好处返回此格式的Andr​​oid是基于区域设置,将翻译工作日。

您将要审查的SimpleDateFormat 了解详情。我觉得这是最干净的方法中,你不需要开关或如果语句,如果你唯一需要的是得到的字符串值。

You will want to review the SimpleDateFormat to learn more. I think this is the cleanest approach in that you do not need a switch or if statement if your only need is to get the string value.