1. 程式人生 > >獲取兩個日期的天數差

獲取兩個日期的天數差

按照時間毫秒的計算

 

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {

    public static void main(String[] args) throws ParseException {
        String startDateStr = "2018-08-20";
        String endDateStr = "2018-09-29";
        int dayNum = differentDays(startDateStr, endDateStr);
        System.out.println(dayNum);
    }

    public static int differentDays(String startDateStr, String endDateStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date endTime = format.parse(endDateStr);
        Date startTime = format.parse(startDateStr);
        int days = (int) ((endTime.getTime() - startTime.getTime()) / (1000 * 3600 * 24));
        return days;
    }

}