小陆每天要写一份工作日报,日报标题含有日期。几年后,他翻开以前的日报,想知道两份日报的日期是否同为星期几,请编程帮助他判断。

题目

小陆每天要写一份工作日报,日报标题含有日期。几年后,他翻开以前的日报,想知道两份日报的日期是否同为星期几,请编程帮助他判断。

输入描述:
第一行一个正整数T(1<=T<=100)。表示有T个测试样例。
接下来T行,每一行有6个正整数y1,m1,d1,y2,m2,d2,(以空格相间)。其中y1-m1-d1分别为第一个日期的年月日,y2-m2-d2分别为第二个日期的年月日。(满足1970<=y1,y2<=9999, 1<=m1,m2<=12, 1<=d1,d2<=31,且保证两个日期是合法的)。

输出描述:
输出T行,对应T个答案。对于每一行,如果两个日期在同一周,输出“True”;否则输出“False”(输出内容不含双引号)。

输入例子1:
2
1970 1 2 2020 2 7
2020 1 1 2020 1 2

输出例子1:
True
False

例子说明1:
1970-1-2和2020-2-7同为星期五;
2020-1-1为星期三,2020-1-2为星期四。

预备知识

时间戳(timestamp)

定义:时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数

Date.getTime()

long preTime=preDate.getTime();//获得毫秒数,不是秒数 1s=1000ms

Java时间转换为时间戳

public static String dateToStamp(String s) throws ParseException{
    String res;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = simpleDateFormat.parse(s);
    long ts = date.getTime();
    res = String.valueOf(ts);
    return res;
}

Java时间戳转时间

public static String stampToDate(String s){
    String res;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    long lt = new Long(s);
    Date date = new Date(lt);
    res = simpleDateFormat.format(date);
    return res;
}

基姆拉尔森计算公式

作用:已知年月日求出星期几
公式:Week = (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400+1) mod 7;
注:把一月和二月看为是上一年的十三月和十四月!
模板:


int Date(int y,int m,int d)
{
    if(m==1||m==2){//一二月换算
        m+=12;
        y--;
    }
    int week = (d + 2*m +3*(m+1)/5 + y + y/4 - y/100 + y/400 + 1)%7;
    return week;//其中1~7表示周一到周日
}

解题思路

如果你知道基姆拉尔森计算公式就可以很快的计算出这个题目的答案了,如果不知道的话,需要注意到题目的一个范围要求1970-01-01,这个时间可以让我们很容易的想到时间戳,所以我们可以计算出2个时间戳只差看是不是可以被10006060247整除。

代码

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws ParseException {
        Scanner sc = new Scanner(System.in);
        int num=sc.nextInt();
        while (num>0){
            int preY=sc.nextInt();int preM=sc.nextInt();int preD=sc.nextInt();
            int lastY=sc.nextInt();int lastM=sc.nextInt();int lastD=sc.nextInt();
            String pre=preY+"-"+preM+"-"+preD;
            String last=lastY+"-"+lastM+"-"+lastD;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date preDate = simpleDateFormat.parse(pre);
            Date lastDate = simpleDateFormat.parse(last);
            long preTime=preDate.getTime();
            long lastTime=lastDate.getTime();
//            System.out.println(preTime);
//            System.out.println(lastTime);
//            System.out.println(lastTime-preTime);
            if((lastTime-preTime)%(604800000)==0){//注意是毫秒
                System.out.println("True");
            }else{
                System.out.println("False");
            }
            num--;
        }

    }
}

原文地址:https://www.cnblogs.com/10134dz/p/13710459.html