猿问

如何计算日期之间的天数

所以我想计算两个日期选择器之间的天数。所以我尝试制作两个数组,但没有任何想法?

这是我的日期选择器


沧海一幻觉
浏览 136回答 4
4回答

杨魅力

public static int getDaysBetweenDates(Date fromDate, Date toDate) {    return Math.abs((int) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24)));}

人到中年有点甜

将日历字符串日、月、年转换为日期类。更多讨论:Java 字符串到日期转换例如DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");Date d1, d2;try {    d1 = dateFormat.parse(year + "-" + month + "-" + day); //as per your example    d2 = //do the same thing as above    long days = getDifferenceDays(d1, d2);} catch (ParseException e) {    e.printStackTrace();}public static long getDifferenceDays(Date d1, Date d2) {long diff = d2.getTime() - d1.getTime();return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);}

慕标5832272

Scanner in = new Scanner(System.in);&nbsp; &nbsp; int n = in.nextInt();&nbsp; &nbsp; Date d1, d2;&nbsp; &nbsp; &nbsp;Calendar cal = Calendar.getInstance();&nbsp; &nbsp; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");&nbsp; &nbsp; sdf.setTimeZone(TimeZone.getTimeZone("UTC"));&nbsp; &nbsp; for (int i = 0; i < n; i++) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d2 = sdf.parse(in.next());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d1 = sdf.parse(in.next());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; long differene = (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Math.abs(differene));&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

qq_花开花谢_0

创建一个方法getDates()private static ArrayList<Date> getDates(String dateString1, String dateString2){&nbsp; &nbsp; ArrayList<Date> arrayofdates = new ArrayList<Date>();&nbsp; &nbsp; DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");&nbsp; &nbsp; Date date1 = null;&nbsp; &nbsp; Date date2 = null;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; date1 = df1 .parse(dateString1);&nbsp; &nbsp; &nbsp; &nbsp; date2 = df1 .parse(dateString2);&nbsp; &nbsp; } catch (ParseException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }&nbsp; &nbsp; Calendar calender1 = Calendar.getInstance();&nbsp; &nbsp; Calendar calendar2 = Calendar.getInstance();&nbsp; &nbsp; calender1.setTime(date1);&nbsp; &nbsp; calender2.setTime(date2);&nbsp; &nbsp; while(!calender1.after(calender2))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; arrayofdates.add(calender1.getTime());&nbsp; &nbsp; &nbsp; &nbsp; calender1.add(Calendar.DATE, 1);&nbsp; &nbsp; }&nbsp; &nbsp; return arrayofdates;}然后在此方法中传递参数以获取日期数组当您使用 DatePicker 然后DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");&nbsp; &nbsp; ArrayList<Date> mBaseDateList = getDates(df1.format(cal1.time), df1.format(cal2.time))
随时随地看视频慕课网APP

相关分类

Java
我要回答