如何使用Datepicker Dialog作为Button计算两个不同的日期

时间:2018-03-17 09:39:41

标签: android datepicker

我使用Datepicker Dialog作为Button计算两个不同的日期时遇到问题。因为我的项目无法解析方法getTimeInMillis()。我希望根据客户数量计算结果。这是我的代码。提前谢谢。

long diff = to.getTimeInMillis() - from.getTimeInMillis();
String total = ""+passenger*diff;

1 个答案:

答案 0 :(得分:0)

以下是解决方案,如何查找2个日期之间的持续时间

    public String differenceDuration(String date1, String date2) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss");

    Date d1 = null;
    Date d2 = null;

    try {
        d1 = format.parse(date1.replace("T"," "));
        d2 = format.parse(date2.replace("T"," "));

        //in milliseconds
        long diff = d2.getTime() - d1.getTime();
        long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;
        long diffDays = diff / (24 * 60 * 60 * 1000);

        System.out.print(diffDays + " days, ");
        System.out.print(diffHours + " hours, ");
        System.out.print(diffMinutes + " minutes, ");
        System.out.print(diffSeconds + " seconds.");

        return ""+hoursDiff+"h "+diffMinutes+"m";
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}