如何获取当前星期几? 有人可以帮我吗?
Calendar
并获取 DAY_OF_WEEK
字段:
Calendar cal = Calendar.getInstance();
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
SimpleDateFormat
:
Date today = Calendar.getInstance().getTime();
DateFormat df = new SimpleDateFormat("EEEE", Locale.ENGLISH); // override the default Locale
String dayNameInWeek = df.format(today);
要获得星期几的文本显示,您可以使用:
DateFormat dateFormat = new SimpleDateFormat("EEEE");
System.out.println("Today is " + dateFormat.format(new Date()));
输出:
Today is Sunday
java.time
2014 年 3 月,Java 8 引入了现代的
java.time
日期时间 API,取代了容易出错的遗留、java.util
日期时间 API。
LocalDate#now
获取今天的日期,然后使用 LocalDate#getDayOfWeek
获取该日期的 enum
常量。您可以使用 DayOfWeek#getDisplayName
获取该常量的文本表示。
演示:
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println(today.getDayOfWeek());
// Get the textual representation of the enum constant
System.out.println(today.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.ENGLISH));
System.out.println(today.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.forLanguageTag("hi-IN")));
System.out.println(today.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.forLanguageTag("bn-BD")));
// Alternatively,
System.out.println(today.format(DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH)));
}
}
输出:
SUNDAY
Sunday
रविवार
রবিবার
Sunday
LocalDate#now
返回系统默认时区中今天的本地日期。使用 LocalDate#now(ZoneId)
获取指定时区今天的本地日期,例如我的系统的默认时区是欧洲/伦敦,目前这里是 2024 年 9 月 22 日星期日 21:30;但现在悉尼时间是 2024 年 9 月 23 日星期一 06:30。如果您使用 LocalDate.now(ZoneId.of("Australia/Sydney"))
运行上述代码,您将得到星期一作为工作日名称。
从 Trail:日期时间了解有关现代日期时间 API 的更多信息。