本月份日历(java代码实现)

代码:

public class CalendarTest{
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        int month = date.getMonthValue();
        int today = date.getDayOfMonth();
        System.out.println(date);
        
        date = date.minusDays(today - 1);
        DayOfWeek weekday = date.getDayOfWeek();
        int value = weekday.getValue();
        System.out.println("Mon Tue Wed Thu Fri Sat Sun");
        for (int i = 1; i < value; i++) {
            System.out.print("    ");
        }
        while (date.getMonthValue() == month){
            System.out.printf("%3d", date.getDayOfMonth());
            if (date.getDayOfMonth() == today) {
                System.out.print("*");
            }else {
                System.out.print(" ");
            }
            date = date.plusDays(1);
            if (date.getDayOfWeek().getValue() == 1) {
                System.out.println();
            }
        }
        if (date. getDayOfWeek().getValue() != 1) {
            System.out.println();
        }
    }
}

运行结果:

今天是8-28日

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是Java代码实现: ```java import java.util.*; public class PrintCalendar { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请输入日期(格式:2022-01):"); String str = input.nextLine(); // 例如输入:2022-01 String[] arr = str.split("-"); int year = Integer.parseInt(arr[0]); int month = Integer.parseInt(arr[1]); input.close(); // 获取当月的天数和第一天是星期几 int days = getDaysOfMonth(year, month); int firstDayOfWeek = getFirstDayOfWeek(year, month); // 输出日历 System.out.println("日\t一\t二\t三\t四\t五\t六"); for (int i = 1; i <= days; i++) { if (i == 1) { for (int j = 0; j < firstDayOfWeek; j++) { System.out.print("\t"); } } System.out.print(i + "\t"); if ((i + firstDayOfWeek) % 7 == 0) { System.out.println(); } } } // 获取当月的天数 public static int getDaysOfMonth(int year, int month) { int days = 0; if (month == 2) { days = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ? 29 : 28; } else if (month == 4 || month == 6 || month == 9 || month == 11) { days = 30; } else { days = 31; } return days; } // 获取当月第一天是星期几(星期日为0,星期一为1,...,星期六为6) public static int getFirstDayOfWeek(int year, int month) { Calendar c = Calendar.getInstance(); c.set(year, month - 1, 1); return c.get(Calendar.DAY_OF_WEEK) - 1; // 对应上面的0~6 } } ``` 使用示例: ``` 请输入日期(格式:2022-01):2022-01 日 一 二 三 四 五 六 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值