如何在Java中找到一个月的第一天的星期几(星期一、星期二等)



例如,如何在Java中找到一周中的哪一天是6月1日?

使用java.util.Date(遗留时间/日期类(:

Date date=new Date(); // today
Date date = new Date(2021, 06, 23); // custom
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); // 3
String dayWeekText = new SimpleDateFormat("EEEE").format(date); //TUESDAY

使用java.time.LocalDate:

LocalDate localDate = LocalDate.of(2021, 06, 23); // custom
LocalDate localDate = LocalDate.now(); // today
java.time.DayOfWeek dayOfWeek = localDate.getDayOfWeek();
dayOfWeek.getValue(); // 4
dayOfWeek.toString(); // WEDNESDAY

如果您希望一周中的某一天为String,则可以使用以下示例中的代码:

public static void main(String[] args) {
// provide the date (alternatively, parse it from a String)
LocalDate firstOfJune2021 = LocalDate.of(2021, 6, 1);
// then get the day of week by means of a DateTimeFormatter
String dayOfWeek = firstOfJune2021.format(
DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH)
);
// as an alternative, you can get it by chain-calling some methods
String altDayOfWeek = firstOfJune2021.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
// print the results
System.out.println(firstOfJune2021 + " was a " + dayOfWeek);
System.out.println(firstOfJune2021 + " was a " + altDayOfWeek);
}

此代码产生以下输出:

2021-06-01 was a Tuesday
2021-06-01 was a Tuesday

有一个enum DayOfWeek,它实际上是LocalDate.getDayOfWeek()的结果类型
从您的问题中不清楚您是否要使用类似intenumString表示的值。。。

这取决于您使用的Java版本和类型。从Java 8开始,使用LocalDate确定一周中哪一天的简单方法如下:

LocalDate date = LocalDate.of(2021, 6, 1);
System.out.println(date.getDayOfWeek().getValue());

返回值的编号从1(星期一(到7(星期日(。

关于不同方法的概述,请参阅"如何在Baeldung上确定一周中的哪一天"。

相关内容

  • 没有找到相关文章

最新更新