java的Calendar类以及判断闰年

7 篇文章 0 订阅

1.Calendar方法

import java.util.Calendar;
/**
 * Created by 一只爱吃萝卜的小兔子 on 2021/11/21 16:07
 */
public class Main{
    public static void main(String[] args) {

        //生成当前日期
        Calendar cal = Calendar.getInstance();
        show(cal);

        //add()方法 +N  -N
        cal.add(Calendar.MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, 1);
        show(cal);
        System.out.println();

        String date = "2019-01-09";
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(5, 7));
        int day = Integer.parseInt(date.substring(8, 10));
        int[] Mons = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int res = 0;

        //set(,);
        //set(年,月,日);
        cal.set(year, 2, 0);//设置零日 记录的是是上个月的最后一天
        show(cal);
        cal.add(Calendar.DAY_OF_MONTH,1);//下个月的第一天
        show(cal);

    }

    private static void show(Calendar cal) {
        //get()方法获取Calendar实例中的数据
        System.out.print(cal.get(Calendar.YEAR) + " ");
        System.out.print(cal.get(Calendar.MONTH) + " ");
        System.out.println(cal.get(Calendar.DAY_OF_MONTH) + " ");
    }
}

2.Calendar判断闰年否,计算输入日期是那一年第几天

import java.util.Calendar;
import java.util.Scanner;

/**
 * Created by 一只爱吃萝卜的小兔子 on 2021/11/21 17:07
 */
public class Main {

    public static void main(String[] args) {
        System.out.println("输入格式:2000-01-12");
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        int day = dayOfYear(s);
        System.out.println(day);
    }
    public static int dayOfYear(String date) {

        //生成当前日期,用于判断是否是闰年
        Calendar cal = Calendar.getInstance();

        //得到年月日
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(5, 7))-1;
        int day = Integer.parseInt(date.substring(8, 10));

        //非闰年月份天数,从0开始
        int[] Mons = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        //记录结果天数
        int res = 0;

        cal.set(year, 2, 0);//设置零日 记录的是year年2月份的最后一天

        //将本月之前的月份加入结果res
        for (int i = 0; i < month; i++) {
            res+=Mons[i];
        }
        // 加入当月的天数
        res=res+day;


        if (cal.get(Calendar.DAY_OF_MONTH) != 29) {//不是闰年

        }else{//是闰年
            if(month>1)//大于二月,被闰年日期影响
            {
                res++;
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值