题目
小陆每天要写一份工作日报,日报标题含有日期。几年后,他翻开以前的日报,想知道两份日报的日期是否同为星期几,请编程帮助他判断。
代码
将输入数据转换为 Date 对象进行判断
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class Main { static StreamTokenizer streamTokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); public static void main(String[] args) throws IOException { int T = nextInt(); while (T-- > 0) { int y1 = nextInt(), m1 = nextInt(), d1 = nextInt(); int y2 = nextInt(), m2 = nextInt(), d2 = nextInt(); Calendar calendar1 = new Calendar.Builder().setDate(y1, m1 - 1, d1).build(); Calendar calendar2 = new Calendar.Builder().setDate(y2, m2 - 1, d2).build(); Date date1 = calendar1.getTime(); Date date2 = calendar2.getTime(); String str1 = String.format(Locale.US, "%ta", date1); String str2 = String.format(Locale.US, "%ta", date2); if (str1.equals(str2)) { System.out.println("True"); } else { System.out.println("False"); } } } static int nextInt() throws IOException { streamTokenizer.nextToken(); return (int) streamTokenizer.nval; } }
基姆拉尔森计算公式
此公式可以用来计算某年某月某日是一周的哪一天,使用此公式时需要将来年的一月和二月转换为今年的十三月和十四月。
W = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) mod 7
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class Main { static StreamTokenizer streamTokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); public static void main(String[] args) throws IOException { int T = nextInt(); while (T-- > 0) { int y1 = nextInt(), m1 = nextInt(), d1 = nextInt(); int y2 = nextInt(), m2 = nextInt(), d2 = nextInt(); if (m1 == 1 || m1 == 2) { m1 += 12; y1--; } if (m2 == 1 || m2 == 2) { m2 += 12; y2--; } int week1 = (d1 + 2 * m1 + 3 * (m1 + 1) / 5 + y1 + y1 / 4 - y1 / 100 + y1 / 400 + 1) % 7; int week2 = (d2 + 2 * m2 + 3 * (m2 + 1) / 5 + y2 + y2 / 4 - y2 / 100 + y2 / 400 + 1) % 7; if (week1 == week2) { System.out.println("True"); } else { System.out.println("False"); } } } static int nextInt() throws IOException { streamTokenizer.nextToken(); return (int) streamTokenizer.nval; } }