java实现某一年某一月某一天是今年的多少天,星期几?

运行截图
日期的很好算,主要是周几比较麻烦。但是只要你知道可以用现在的总天数(现在到1年1月1日)对7取余,就很简单了。
还有就是记得考虑闰年,闰年的公式是整除4不整除100或者整除400.下面是详细代码:

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        if (str == null || str.length() == 0) {
            System.out.println("输入不合法!");
        }
        assert str != null;
        String[] strings = str.split("-");
        int year = Integer.parseInt(strings[0]);
        int month = Integer.parseInt(strings[1].replace("0", ""));
        int[] arr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int day = Integer.parseInt(strings[2].replace("0", ""));
        for (int i = 0; i < month - 1; i++) {
            day = day + arr[i];
        }
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            if (month >= 3) {
                day = day + 1;
            }
        }
        System.out.println(day+"天,星期"+weekday(year,day));
    }

    public static String weekday(int year,int day){
        long amount=0;
        for(int i=1;i<year;i++){
            if((i % 4 == 0 && i % 100 != 0) || i % 400 == 0)
                amount++;
        }
        amount+= 365L *(year-1);
        amount+=day;
        int week=(int) (amount%7);
        String w="";
        switch(week){
            case 0:w="日";break;
            case 1:w="一";break;
            case 2:w="二";break;
            case 3:w="三";break;
            case 4:w="四";break;
            case 5:w="五";break;
            case 6:w="六";break;
        }
        return w;
    }
}

我这块是面试的时候随手写在main方法里面了,可以自己抽取成单独的方法去使用。项目中还是建议直接使用Data和Calendar类去操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值