计算android中两个日期之间的周数

时间:2016-12-18 17:18:25

标签: java android

如何计算android中两个日期之间的周数?我做过类似的事情

FormBuilder

但是,当两个日期在不同年份时,这不起作用。如何实现解决方案以使其在不同年份中发挥作用?

修改

我尝试过使用jodatime进行以下操作

FormControl

这几乎可行,但出于某种原因,它认为本周的开始是星期四。我希望本周开始时间为周一,以便周一至周六返回0(同一周),但周六至周日将返回1(不同周)

8 个答案:

答案 0 :(得分:1)

public int getWeekDifference(long fromDateInMills, long toDateInMills) {

    int weeks = Weeks.weeksBetween(new DateTime(fromDateInMills), new DateTime(toDateInMills)).getWeeks();

    // when we select any future date than week difference comes in negative so
    // just interchange millisecond You will get week difference in positive
    if (weeks < 0) {
        weeks = Weeks.weeksBetween(new DateTime(toDateInMills), new DateTime(fromDateInMills)).getWeeks();
    }

    return weeks;

}

答案 1 :(得分:1)

这里有些答案给出了错误的结果,有些需要额外的库。我设法想出了一种使用标准 Calendar API 计算周差的方法。

它可以正确处理 2000-01-01 to 2000-12-31 之类的边缘情况(54 周意味着相差 53)。

getWeeksBetween() 使用 Calendar API

public static int getWeeksBetween(final Date start, final Date end) {
    final Calendar c1 = Calendar.getInstance(Locale.US);
    final Calendar c2 = Calendar.getInstance(Locale.US);

    // Skip time part! Not sure if this is needed, but I wanted clean dates.
    CalendarUtils.setDateWithNoTime(c1, start);
    CalendarUtils.setDateWithNoTime(c2, end);

    CalendarUtils.goToFirstDayOfWeek(c1);
    CalendarUtils.goToFirstDayOfWeek(c2);

    int weeks = 0;
    while (c1.compareTo(c2) < 0) {
        c1.add(Calendar.WEEK_OF_YEAR, 1);
        weeks++;
    }

    return weeks;
}

还有一些辅助方法:

public static int goToFirstDayOfWeek(final Calendar calendar) {
    final int firstDayOfWeek = calendar.getFirstDayOfWeek();
    calendar.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);

    return firstDayOfWeek;
}

public static void setDateWithNoTime(final Calendar calendar, final Date date) {
    calendar.setTime(date);
    clearTime(calendar);
}

public static void clearTime(final Calendar calendar) {
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
}

答案 2 :(得分:0)

在不使用JodaTime的情况下,我想出了以下解决方案来计算周数:

private fun calculateNumberOfWeeks() {
    val calendarFrom = Calendar.getInstance()
    calendarFrom.set(Calendar.HOUR_OF_DAY, 0)
    calendarFrom.set(Calendar.MINUTE, 0)
    calendarFrom.set(Calendar.SECOND, 0)
    calendarFrom.set(Calendar.MILLISECOND, 0)

    val calendarTo = Calendar.getInstance()
    calendarTo.add(Calendar.MONTH, months)
    calendarTo.set(Calendar.HOUR_OF_DAY, 0)
    calendarTo.set(Calendar.MINUTE, 0)
    calendarTo.set(Calendar.SECOND, 0)
    calendarTo.set(Calendar.MILLISECOND, 0)

    var weeks = -1
    while (calendarFrom.timeInMillis < calendarTo.timeInMillis) {
        calendarFrom.add(Calendar.DATE, 7)
        weeks++
        Log.d(Constants.LOG_TAG, "weeks $weeks")
    }
}

答案 3 :(得分:0)

我建议您不要尝试以周为单位计算差异,而应尝试以天为单位查找差异,然后将结果除以7。

所以应该是几周=(daysBetweenDates / 7)

答案 4 :(得分:0)

使用Java 8

公共无效week_between_two_dates_in_java_with_java8(){

var res = await getFromAPI();
setState(() {
    listToPopulate = res;
});

}

或使用joda时间api

LocalDate startDate = LocalDate.of(2005, Month.JANUARY, 1);
LocalDate endDate = LocalDate.of(2006, Month.JANUARY, 1);

long weeksInYear = ChronoUnit.WEEKS.between(startDate, endDate);

答案 5 :(得分:0)

那种只用数学的低技术解决方案呢?

每个日期都有Week_OF_YEAR。还有每个的YEAR编号。 将每个Year数字乘以52,将其添加到WEEK_OF_YEAR,然后减去两个数字。 例如.... 2018第50周 至 2019一周2

2018 * 52 = 104936 + 50周= 104986
2019 * 52 = 104988 + 2周= 104990

104990-104986 = 4周

答案 6 :(得分:0)

另一种替代解决方案。我的基本概念是:

  1. 将给定的日期修剪为相应的星期一 00:00:00.000
  2. 计算这些修剪日期之间的毫秒数,然后除以一周的毫秒数。

Java 示例:

public class Main {
    
    public static void main(String[] args) {
        Calendar Monday = Calendar.getInstance();
        Monday.set(2020, 11, 28, 12, 34, 56); // 2020-12-28T12:34:56
        Calendar Saturday = Calendar.getInstance();
        Saturday.set(2021, 0, 2, 21, 43, 57); // 2021-01-02T21:43:57
        Calendar Sunday = Calendar.getInstance();
        Sunday.set(2021, 0, 3, 0, 1, 2); // 2021-01-03T00:01:02
        Calendar NextMonday = Calendar.getInstance();
        NextMonday.set(2021, 0, 4, 1, 23, 45); // 2021-01-04T01:23:45
        
        System.out.println(String.format(": %d week(s)", weeksTouched(Monday, Sunday)));
        System.out.println(String.format(": %d week(s)", weeksTouched(Saturday, Sunday)));
        System.out.println(String.format(": %d week(s)", weeksTouched(Sunday, NextMonday)));
    }
    
    public static int weeksTouched(Calendar fromDate, Calendar toDate){
        System.out.print(String.format("%s -> %s", fromDate.getTime(), toDate.getTime()));
        return (int) (
                (trimToMonday(toDate).getTimeInMillis() - trimToMonday(fromDate).getTimeInMillis())
                / (1000 * 60 * 60 * 24 * 7)
                );
    }
    
    private static Calendar trimToMonday(Calendar input) {
        Calendar output = (Calendar) input.clone();
        
        switch (output.get(Calendar.DAY_OF_WEEK)) {
        case Calendar.TUESDAY:
            output.add(Calendar.DAY_OF_MONTH, -1);
            break;
        case Calendar.WEDNESDAY:
            output.add(Calendar.DAY_OF_MONTH, -2);
            break;
        case Calendar.THURSDAY:
            output.add(Calendar.DAY_OF_MONTH, -3);
            break;
        case Calendar.FRIDAY:
            output.add(Calendar.DAY_OF_MONTH, -4);
            break;
        case Calendar.SATURDAY:
            output.add(Calendar.DAY_OF_MONTH, -5);
            break;
        case Calendar.SUNDAY:
            output.add(Calendar.DAY_OF_MONTH, -6);
            break;
        }
        
        output.set(Calendar.HOUR_OF_DAY, 0);
        output.set(Calendar.MINUTE, 0);
        output.set(Calendar.SECOND, 0);
        output.set(Calendar.MILLISECOND, 0);
        
        return output;
    }
}

输出:

Mon Dec 28 12:34:56 JST 2020 -> Sun Jan 03 00:01:02 JST 2021: 0 week(s)
Sat Jan 02 21:43:57 JST 2021 -> Sun Jan 03 00:01:02 JST 2021: 0 week(s)
Sun Jan 03 00:01:02 JST 2021 -> Mon Jan 04 01:23:45 JST 2021: 1 week(s)

答案 7 :(得分:-1)

这将为您提供两个星期的b / w两个星期。

  public void getNoOfWeek()
    {

        Calendar date1 = Calendar.getInstance();
        Calendar date2 = Calendar.getInstance();

        date1.clear();
        date1.set(2015, 12, 29); // set date 1 (yyyy,mm,dd)
        date2.clear();
        date2.set(2016, 02, 7); //set date 2 (yyyy,mm,dd)

        long diff = date2.getTimeInMillis() - date1.getTimeInMillis();

        float dayCount = (float) diff / (24 * 60 * 60 * 1000);

        int week = (int) (dayCount / 7);
        System.out.println(week);
    }