输入年-月-日,判断这一天是这一年的第几天

题目要求:日期格式 年-月-日 如: 2016-09-07
//Scanner读取如上格式返回String类型数据,需转化为int进行之后的运算
//判断天数需要考虑到闰年的问题
//计算天数
看了网上其他的方法,我计算天数的方法还是比较简洁的。

import java.util.Scanner;
public class Day07 {
    public static void main(String[] args) {
        // 1 截取字符串、转化为int,得到日期数据 年月日分别用y m d存储
        Scanner sc = new Scanner(System.in);
        int y, m, d;
        String s, sy, sm, sd;
        System.out.print("请输入日期(年-月-日):");
        s = sc.nextLine();
        sy = s.substring(0, 4);
        sm = s.substring(5, 7);
        sd = s.substring(8, 10);
        y = Integer.parseInt(sy, 10);
        m = Integer.parseInt(sm, 10);
        d = Integer.parseInt(sd, 10);
        // 2 判断是否闰年 并用 days 数组存储每月天数
        boolean isLeap = false;
        if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) {
            isLeap = true;
        }
        int[] days = new int[12];
        if (isLeap) {
            days = new int[] { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        } else {
            days = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        }
        // 3 计算天数daysOfYear
        int daysOfYear = d;
        for (int i = 0; i < m - 1; i++) {
            daysOfYear += days[i];
        }
        System.out.println("今天是" + y + "年的第" + daysOfYear + "天");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值