日常练习-2017年2月7日

本文介绍了一段Java代码,该代码能够将用户输入的日期(格式为YYYY-MM-DD)转换为当年的第几天。通过解析输入的日期字符串,确定年、月、日,并计算截至指定月份每个月的总天数来实现此功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入一个日期,判断当前日期在当前年份是第几天?

代码如下:

package testCase;

import java.util.Scanner;

public class JudgeDayOfYear {
    /* 输入某年某月某日,判断这一天是这一年的第几天? */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);// 创建输入流扫描器
        System.out.println("请输入YYYY-MM-DD格式的日期字符串:");
        String line = scanner.nextLine();// 获取用户输入的一行文本
        int i = orderDate(line);
        System.out.println("输入的日期是当前年的第" + i + "天");
        scanner.close();
    }

    public static int orderDate(String dateStr) {
        int dateSum = 0;
        int year = Integer.valueOf(dateStr.substring(0, 4));
        int month = Integer.valueOf(dateStr.substring(5, 7));
        int day = Integer.valueOf(dateStr.substring(8, 10));
        for (int i = 1; i < month; i++) {
            switch (i) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                dateSum += 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                dateSum += 30;
                break;
            case 2:
                if (((year % 4 == 0) & (year % 100 != 0)) | (year % 400 == 0))
                    dateSum += 29;
                else
                    dateSum += 28;
            }
        }

        return dateSum = dateSum + day;
    }
}`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值