Java計算兩個字符串日期之間的天數差


Java計算兩個字符串日期之間的天數差

調用方法:

    public static void main(String[] args) throws ParseException {

        String a = "2017-12-01"; // 時間字符串
        String b = "2017-12-31";

        Long between_dayInteger = between_days(a, b);

        System.out.println(between_dayInteger);

    }

控制台輸出:

封裝方法:

public static Long between_days(String a, String b) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 自定義時間格式

        Calendar calendar_a = Calendar.getInstance();// 獲取日歷對象
        Calendar calendar_b = Calendar.getInstance();

        Date date_a = null;
        Date date_b = null;

        try {
            date_a = simpleDateFormat.parse(a);//字符串轉Date
            date_b = simpleDateFormat.parse(b);
            calendar_a.setTime(date_a);// 設置日歷
            calendar_b.setTime(date_b);
        } catch (ParseException e) {
            e.printStackTrace();//格式化異常
        }

        long time_a = calendar_a.getTimeInMillis();
        long time_b = calendar_b.getTimeInMillis();

        long between_days = (time_b - time_a) / (1000 * 3600 * 24);//計算相差天數

        return between_days;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM