我想要一个Java程序来计算两个日期之间的天数。
如何包含include年和夏季?
我的代码:
import java.util.Calendar; import java.util.Date; import java.util.Scanner; public class NewDateDifference { public static void main(String[] args) { System.out.print("Insert first date: "); Scanner s = new Scanner(System.in); String[] eingabe1 = new String[3]; while (s.hasNext()) { int i = 0; insert1[i] = s.next(); if (!s.hasNext()) { s.close(); break; } i++; } System.out.print("Insert second date: "); Scanner t = new Scanner(System.in); String[] insert2 = new String[3]; while (t.hasNext()) { int i = 0; insert2[i] = t.next(); if (!t.hasNext()) { t.close(); break; } i++; } Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(insert1[0])); cal.set(Calendar.MONTH, Integer.parseInt(insert1[1])); cal.set(Calendar.YEAR, Integer.parseInt(insert1[2])); Date firstDate = cal.getTime(); cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(insert2[0])); cal.set(Calendar.MONTH, Integer.parseInt(insert2[1])); cal.set(Calendar.YEAR, Integer.parseInt(insert2[2])); Date secondDate = cal.getTime(); long diff = secondDate.getTime() - firstDate.getTime(); System.out.println ("Days: " + diff / 1000 / 60 / 60 / 24); } }
你正在使用你的字符串进行一些不必要的转换。有一个SimpleDateFormat类-试试这个:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy"); String inputString1 = "23 01 1997"; String inputString2 = "27 04 1997"; try { Date date1 = myFormat.parse(inputString1); Date date2 = myFormat.parse(inputString2); long diff = date2.getTime() - date1.getTime(); System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS)); } catch (ParseException e) { e.printStackTrace(); }
编辑:既然有一些关于此代码的正确性的讨论:它确实照顾care年。但是,TimeUnit.DAYS.convert由于毫秒转换为天,因此该函数失去了精度(有关更多信息,请参见链接的文档)。如果有问题,diff也可以手动转换:
float days = (diff / (1000*60*60*24));
请注意,这是一个float值,不一定是int。
float
int