为了账号安全,请及时绑定邮箱和手机立即绑定

如何计算日期之间的天数

如何计算日期之间的天数

沧海一幻觉 2022-07-20 20:31:34
所以我想计算两个日期选择器之间的天数。所以我尝试制作两个数组,但没有任何想法?这是我的日期选择器
查看完整描述

4 回答

?
杨魅力

TA贡献1811条经验 获得超6个赞

public static int getDaysBetweenDates(Date fromDate, Date toDate) {

    return Math.abs((int) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24)));

}


查看完整回答
反对 回复 2022-07-20
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

将日历字符串日、月、年转换为日期类。

更多讨论: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);

}


查看完整回答
反对 回复 2022-07-20
?
慕标5832272

TA贡献1966条经验 获得超4个赞

Scanner in = new Scanner(System.in);

    int n = in.nextInt();

    Date d1, d2;

     Calendar cal = Calendar.getInstance();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    for (int i = 0; i < n; i++) {

        try {

            d2 = sdf.parse(in.next());

            d1 = sdf.parse(in.next());

            long differene = (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24);

            System.out.println(Math.abs(differene));

        } catch (Exception e) {

        }

    }


查看完整回答
反对 回复 2022-07-20
?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

创建一个方法getDates()


private static ArrayList<Date> getDates(String dateString1, String dateString2)

{

    ArrayList<Date> arrayofdates = new ArrayList<Date>();

    DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");


    Date date1 = null;

    Date date2 = null;


    try {

        date1 = df1 .parse(dateString1);

        date2 = df1 .parse(dateString2);

    } catch (ParseException e) {

        e.printStackTrace();

    }


    Calendar calender1 = Calendar.getInstance();

    Calendar calendar2 = Calendar.getInstance();

    calender1.setTime(date1);

    calender2.setTime(date2);


    while(!calender1.after(calender2))

    {

        arrayofdates.add(calender1.getTime());

        calender1.add(Calendar.DATE, 1);

    }

    return arrayofdates;

}

然后在此方法中传递参数以获取日期数组当您使用 DatePicker 然后


DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");

    ArrayList<Date> mBaseDateList = getDates(df1.format(cal1.time), df1.format(cal2.time))



查看完整回答
反对 回复 2022-07-20
  • 4 回答
  • 0 关注
  • 135 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号