如何检索当前星期几?

问题描述 投票:0回答:3

如何获取当前星期几? 有人可以帮我吗?

java date simpledateformat dayofweek
3个回答
3
投票

使用

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

0
投票

要获得星期几的文本显示,您可以使用:

DateFormat dateFormat = new SimpleDateFormat("EEEE");
System.out.println("Today is " + dateFormat.format(new Date()));

输出:

Today is Sunday

0
投票

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 的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.