两次之间的差值为0

时间:2019-05-22 08:22:57

标签: java android datetime

在找到两个日期之间的差异时获得0的结果。

我从消防站得到接客时间。 Firestore查询运行正常。

控制台结果

      D/TAG: 01:09:50 pm == 12:09:00 pm.
      I/======= difference: 0
      I/======= Hours:  :: 0==mint0

代码

{
     SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss a");

     date1 = format.parse(pickupTime);
     date2 = format.parse(current_time);

     Log.d(TAG, current_time + "==" + pickupTime);

     long difference = date1.getTime() - date1.getTime();
     Log.i("======= difference",String.valueOf(difference));

     int days = (int) (difference / (1000*60*60*24));
     int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60));
     int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
     hours = (hours < 0 ? -hours : hours);

     Log.i("======= Hours"," :: "+hours +"==mint"+min);
}

3 个答案:

答案 0 :(得分:1)

我建议使用ChronoUnit来计算差异。为我工作。像这样:

package test;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;


public class Test3 {

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

        System.out.println(calculateDurationBetween(LocalDateTime.now().minusHours(2).minusMinutes(4).minusSeconds(14), LocalDateTime.now()));

    }


    public static String calculateDurationBetween(LocalDateTime start, LocalDateTime end) {
        if (start != null && end != null) {
            //long days = ChronoUnit.DAYS.between(start, end);
            //minutes over the full days (started day)
            long hours = ChronoUnit.HOURS.between(start, end) % 24;
            long minutes = ChronoUnit.MINUTES.between(start, end) % 60;
            long seconds = ChronoUnit.SECONDS.between(start, end) % 60;
            return hours+":"+minutes+":"+seconds;
        }
        return null;
    }

}

答案 1 :(得分:1)

更改以下内容:

dir

收件人:

  long difference = date1.getTime() - date1.getTime();

答案 2 :(得分:0)

如果要以毫秒为单位进行差异:

long difference = date2.getTime() - date1.getTime();

如果希望以天,小时,分钟,秒为单位:用于获取日期之间的差异(此处date2可以是用户选择的日期,date1可以是当前日期时间(您可以致电:new Date()))

public static String getDifferenceBetweenDates(Date date1, Date date2) {
    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long difference = date2.getTime() - date1.getTime();

    long elapsedDays = difference / daysInMilli;
    difference = difference % daysInMilli;

    long elapsedHours = difference / hoursInMilli;
    difference = difference % hoursInMilli;

    long elapsedMinutes = difference / minutesInMilli;
    difference = difference % minutesInMilli;

    long elapsedSeconds = difference / secondsInMilli;

    return String.format("%s days %s hours %s minutes %s seconds", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}