【发布时间】:2021-03-11 13:26:55
【问题描述】:
我正在努力计算每月 1 日的星期日数。 就像输入 1(测试用例)1900 1 1 1902 1 1(年、月、日)一样,输出应该是 4。包括开始日期。
解释:
1 April 1900
1 July 1900
1 September 1901
1 December 1901
但是,当我尝试这样做时:
6 4699 12 12 4710 1 1 1988 3 25 1989 7 13 1924 6 6 1925 6 16 1000000000000 2 2 1000000001000 3 2 1925 6 16 1924 6 6 1905 1 1 1905 1 1
输出应该是:18 2 2 1720 0 1
我的代码输出是:18 2 2 **1714** 0 1
在测试输入中,6 表示 6 个测试用例。 4699 年 12 个月 12 天,所以 4699 年 12 月 12 日; 4710结束日期等等。
你能帮我解决这个问题吗?
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
public class nineteen {
public static void main(String[] args) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Scanner sc = new Scanner(System.in);
int loop = sc.nextInt();
for (int i = 0; i < loop; i++) {
long year = sc.nextLong(), month = sc.nextLong(), day = sc.nextLong(), yearto = sc.nextLong(),
monthto = sc.nextLong(), dayto = sc.nextLong();
String day1 = String.valueOf(day);
String month1 = String.valueOf(month);
String year1 = String.valueOf(year);
String dayt = String.valueOf(dayto);
String montht = String.valueOf(monthto);
String yeart = String.valueOf(yearto);
String input_date = month1 + "/" + day1 + "/" + year1; // month day year
String out_date = montht + "/" + dayt + "/" + yeart; // month day year
long count = 0;
Date d1 = formatter.parse(input_date);
Date d2 = formatter.parse(out_date);
count = saturdayscount(d1, d2);
// TODO Auto-generated method stub
}
sc.close();
}
public static long saturdayscount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
long sundays = 0;
while (!c1.after(c2)) {
if (c1.get(Calendar.DAY_OF_MONTH) != 1) {
c1.add(Calendar.MONTH, 1);
c1.set(Calendar.DAY_OF_MONTH, 1);
}
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
sundays++;
}
c1.add(Calendar.MONTH, 1);
c1.set(Calendar.DAY_OF_MONTH, 1);
}
System.out.println(sundays);
return sundays;
}
}
【问题讨论】:
-
包括开始日期和结束日期吗?
-
我不太确定(因为你没有回答我的问题),但我认为数字 1000000000000 和 1000000001000 应该是年。如果是这样,您将超出
Date支持的范围。这就是Date类的混乱程度,它不会提示您错误,它只是选择一些在其范围内的日期,并且与您想要的日期没有可识别的关系。 -
@OleV.V.这是测试输入 6 均值是测试用例 4699 年 12 月 12 天; 4710 结束日期等等。是的,包括开始日期。我找不到日期类的范围。能给个链接吗感谢您的贡献。
-
你是对的,它没有直接记录。
Date在内部表示为long,表示与 1970-01-01T00:00:00Z (UTC) 的“纪元”之间的毫秒差。new Date(Long.MAX_VALUE)在我的电脑上打印Sun Aug 17 08:12:55 CET 292278994,所以这是上限。下限是new Date(Long.MIN_VALUE)或Sun Dec 02 17:47:04 CET 292269055,其中年份是 BCE。
标签: java date date-format java-time