亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何計算日期之間的天數

如何計算日期之間的天數

滄海一幻覺 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 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號