安卓日历以字符串形式获取当前星期几

2022-09-01 02:44:40

我试图以这种方式获取具有实际工作日名称的字符串:

            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,所以我应该等于weekDaydayOfWeekc.get(Calendar.THURSDAY)


答案 1

就这么简单

sCalendar = Calendar.getInstance();
String dayLongName = sCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());

答案 2

我通过执行以下操作实现了此目的:

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

Calendar calendar = Calendar.getInstance();
weekDay = dayFormat.format(calendar.getTime());
  • 使用“EEEE”的日期格式将返回完整的工作日名称,即星期二
  • 使用“E”的日期格式将返回缩写名称,即 Tue
  • 在Android中返回此格式的另一个好处是,它将根据区域设置翻译工作日。

您将需要查看SimpleDateFormat以了解更多信息。我认为这是最干净的方法,因为您不需要开关if语句,如果您唯一需要的是获取字符串值。