java在控制台打印出本月所有星期六的日期,按照yyyy年MM月dd日的格式输出
时间: 2023-06-11 19:05:18 浏览: 189
Java打印日历
好的,让我来为您解决这个问题。
首先,我们需要获取当前月份和年份:
```java
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
```
然后,我们可以使用循环遍历一个月的每一天,判断每一天是否为星期六,如果是星期六,就输出日期。
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
for (int i = 1; i <= 31; i++) {
cal.set(year, month - 1, i);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY) {
System.out.println(sdf.format(cal.getTime()));
}
}
```
完整的代码如下:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
for (int i = 1; i <= 31; i++) {
cal.set(year, month - 1, i);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY) {
System.out.println(sdf.format(cal.getTime()));
}
}
}
}
```
希望能够帮助到您!
阅读全文