java - 如何考虑java中的夏令时计算两个日期之间的全天差

标签 java android date calendar jodatime

我需要在java中获取两个日期之间的完整天数(日期以日期类型给出)。
例如: 01/01/2015/12:00:00 - 01/02/2015/11:59:00 不是一整天 我需要考虑夏令时。
我知道 jodatime lib 可以做到这一点,但我达到了 65k 方法限制,并且无法使用 jodatime lib。
我尝试了毫秒 diff 方式和使用“before”方法的 while 循环: Android/Java - Date Difference in days

最佳答案

我设法弄清楚: 我使用了一些代码 - https://stackoverflow.com/a/28865648/3873513 并添加了我的一些内容:

     public static int calcDaysDiff(Date day1, Date day2) {
    Date d1 = new Date(day1.getTime());
    Date d2 = new Date(day2.getTime());
    Calendar date1 = Calendar.getInstance();
    date1.setTime(d1);
    Calendar date2 = Calendar.getInstance();
    date2.setTime(d2);
    //checks if the start date is later then the end date - gives 0 if it is
    if (date1.get(Calendar.YEAR) >= date2.get(Calendar.YEAR)) {
        if (date1.get(Calendar.DAY_OF_YEAR) >= date2.get(Calendar.DAY_OF_YEAR)) {
            return 0;
        }
    }
    //checks if there is a daylight saving change between the two dates

    int offset = calcOffset(d1, d2);

    if (date1.get(Calendar.YEAR) > date2.get(Calendar.YEAR)) {
        //swap them
        Calendar temp = date1;
        date1 = date2;
        date2 = temp;
    }

    return calcDaysDiffAux(date1, date2) + checkFullDay(date1, date2, offset);
}

// check if there is a 24 hour diff between the 2 dates including the daylight saving offset
public static int checkFullDay(Calendar day1, Calendar day2, int offset) {
    if (day1.get(Calendar.HOUR_OF_DAY) <= day2.get(Calendar.HOUR_OF_DAY) + offset) {
        return 0;
    }
    return -1;
}

// find the number of days between the 2 dates. check only the dates and not the hours
public static int calcDaysDiffAux(final Calendar day1, final Calendar day2) {
    Calendar dayOne = (Calendar) day1.clone(),
            dayTwo = (Calendar) day2.clone();

    if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
        return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
    } else {

        int extraDays = 0;

        while (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
            dayTwo.add(Calendar.YEAR, -1);
            // getActualMaximum() important for leap years
            extraDays += dayTwo.getActualMaximum(Calendar.DAY_OF_YEAR);
        }

        return extraDays - day1.get(Calendar.DAY_OF_YEAR) + day2.get(Calendar.DAY_OF_YEAR);
    }
}

关于java - 如何考虑java中的夏令时计算两个日期之间的全天差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32770083/

相关文章:

java - 解析和组织 GovTrack API JSON 数据

android - 在Android上下载youtube

java - 日期格式中月和日的固定长度?

java - Hibernate 4.1 Hibernate.STRING 的最终替代方案

java - 关于java虚方法的问题

java - 为什么 urlconnection 没有读取完整的响应

java - 语法错误 : Insert "}" to complete block

java - 在 Java 中使用 Date 为用户设置随机日期?

c# - 如何使用 Spring-objects 在 XML v1.0 中的对象属性中设置当前日期?

java - Eclipse 可以自动生成第三方库类的接口(interface)吗?