java处理某一天到n个月某一天的实现方法

 /**
     * 取得系统当前时间后n个月的相对应的一天
     *
     * @param n int
     * @return String     yyyy-mm-dd
     */
    public String getNMonthAfterCurrentDay(int n) {
        Calendar c = Calendar.getInstance();
        c.add(c.MONTH, n);
        return "" + c.get(c.YEAR) + "-" + (c.get(c.MONTH) + 1) + "-" + c.get(c.DATE);

    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java实现的代码: ```java import java.util.Scanner; public class MotherDay { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入年份:"); int year = sc.nextInt(); sc.close(); int month = 5; // 母亲节固定在5 int day = getMotherDay(year, month); System.out.println(year + "年的母亲节是" + month + "" + day + "日"); // 在历中标注母亲节 printMonth(year, month, day); } // 计算母亲节的日期 public static int getMotherDay(int year, int month) { int day = 1; // 从1号开始查找 int week = getWeekDay(year, month, day); while (week != 0) { // 找到第一个星期日 day++; week = getWeekDay(year, month, day); } return day + 7; // 第二个星期日就是母亲节 } // 计算某一天是星期几 public static int getWeekDay(int year, int month, int day) { if (month == 1 || month == 2) { year--; month += 12; } int c = year / 100; int y = year % 100; int week = (c / 4 - 2 * c + y + y / 4 + 13 * (month + 1) / 5 + day - 1) % 7; if (week < 0) { week += 7; } return week; } // 在历中标注母亲节 public static void printMonth(int year, int month, int day) { String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // 判断闰年 if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { daysInMonth[1] = 29; } // 打印历 System.out.println("\n " + monthName[month - 1] + " " + year); System.out.println("------------------------------"); System.out.println(" Sun Mon Tue Wed Thu Fri Sat"); int weekDay = getWeekDay(year, month, 1); for (int i = 0; i < weekDay; i++) { System.out.print(" "); } for (int i = 1; i <= daysInMonth[month - 1]; i++) { if (i == day) { System.out.printf("|%2d|", i); // 标注母亲节 } else { System.out.printf("%4d", i); } weekDay = (weekDay + 1) % 7; if (weekDay == 0) { System.out.println(); } } System.out.println(); } } ``` 运行结果如下: ``` 请输入年份:2022 2022年的母亲节是58日 May 2022 ------------------------------ Sun Mon Tue Wed Thu Fri Sat 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、付费专栏及课程。

余额充值