如何计算日期之间的天数

时间:2019-03-06 09:51:58

标签: java android date days date-difference

所以我想计算两个日期选择器之间的间隔天数。 所以我试图做两个数组,但没有用 有任何想法吗?

这是我的约会选择器

4 个答案:

答案 0 :(得分:0)

将日历字符串的日,月,年转换为Date类。

此处有更多讨论:https://pygithub.readthedocs.io/en/latest/apis.html

例如

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);
}

答案 1 :(得分:0)

创建方法 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))

答案 2 :(得分:0)

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) {
        }
    }

答案 3 :(得分:0)

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