【问题标题】:Get the number of weeks between two Dates.获取两个日期之间的周数。
【发布时间】:2012-04-15 07:54:18
【问题描述】:

我在一个项目中工作,我在 Date 中有两种类型。我想计算这两个日期之间的周数。日期可以在不同的年份。有什么好的解决方案吗?

我已尝试使用其他主题中建议的 Joda-time 来实现这一点..

我不熟悉这个库,但我尝试做这样的事情:

public static int getNumberOfWeeks(Date f, Date l){
    Calendar c1 = Calendar.getInstance();
    Calendar c2 = Calendar.getInstance();
    c1.setTime(f);
    c2.setTime(l);
    DateTime start = new DateTime(c1.YEAR, c1.MONTH, c1.DAY_OF_MONTH, 0, 0, 0, 0);
    DateTime end   = new DateTime(c2.YEAR, c2.MONTH, c2.DAY_OF_MONTH, 0, 0, 0, 0);
    Interval interval = new Interval(start, end);
    Period p = interval.toPeriod();
    return p.getWeeks();
}

但这是完全错误的......有什么建议吗?

【问题讨论】:

标签: java date jodatime


【解决方案1】:

更新答案以说明 Java 8

// TechTrip - ASSUMPTION d1 is earlier than d2
// leave that for exercise
public static long getFullWeeks(Calendar d1, Calendar d2){

    Instant d1i = Instant.ofEpochMilli(d1.getTimeInMillis());
    Instant d2i = Instant.ofEpochMilli(d2.getTimeInMillis());

    LocalDateTime startDate = LocalDateTime.ofInstant(d1i, ZoneId.systemDefault());
    LocalDateTime endDate = LocalDateTime.ofInstant(d2i, ZoneId.systemDefault());

    return ChronoUnit.WEEKS.between(startDate, endDate);
}

【讨论】:

  • 请注意,开始日期始终包括在内,而结束日期不包括在内。
  • 这里如果我给出 2018 年 2 月 28 日和 2019 年 3 月 2 日,它计算 1 周,它应该计算 2 周。你帮我算算吗?
  • @IrfanNasim 正是我要找的。你找到解决方案了吗?
  • LocalDateTime 不能代表时刻,即时间线上的特定点。所以在这里使用是不合适的。替换为ZonedDateTime 做一个更好的例子。
【解决方案2】:

joda time 很容易:

DateTime dateTime1 = new DateTime(date1);
DateTime dateTime2 = new DateTime(date2);

int weeks = Weeks.weeksBetween(dateTime1, dateTime2).getWeeks();

【讨论】:

  • 正确答案,但已过时。 Joda-Time 的创建者说我们应该迁移到 java.time 框架。
  • 在这种情况下为真,但不是一个选项,例如,如果您依赖 Interval 类。在 java.time 中没有其他选择。
  • 您会在扩展 java.time 的 ThreeTen-Extra 项目中找到一个 Interval 类。 ThreeTen-Extra 还作为未来可能添加到 java.time 类的试验场。但是,Joda-Time 和 java.time 并不是 100% 的功能对等。虽然大致相同,但每个都有一些其他缺少的功能。
  • 关于 Threeten-Extra,它似乎几乎处于休眠状态(参见低活动,甚至还没有替代 Jodas PeriodFormatter)。另一种具有间隔支持等的替代方法可以在我的 lib Time4J 中找到,它可以与 java.time-package 互操作,也可以用作扩展。
【解决方案3】:

tl;博士

ChronoUnit
.WEEKS
.between(
    myJavaUtilDate_Start.toInstant().atZone( ZoneId.of( "Asia/Tokyo" ) ) , 
    myJavaUtilDate_Stop.toInstant().atZone( ZoneId.of( "Asia/Tokyo" ) ) 
)

7

java.time

java.time 框架内置于 Java 8 及更高版本中。这些新类取代了与 Java 的最早版本捆绑在一起的旧日期时间类。

java.time 类也取代了非常成功的Joda-Time 框架。 java.timeJoda-Time 均由 Stephen Colbourne 领导。

Instant 替换 java.util.Date

现代类Instant 替换了旧类java.util.Date。两者都代表 UTC 中的一个时刻,即时间线上的一个特定点。两者在内部都使用自 1970 年第一刻(UTC,1970-01-01T00:00Z)的同一纪元参考以来的计数。旧类使用毫秒计数,而Instant 使用更精细的纳秒计数。

要转换,请调用添加到旧类的新方法。

Instant start = myJavaUtilDateStart.toInstant() ;
Instant stop = myJavaUtilDateStop.toInstant() ;

让我们用一些示例值来具体化。

Instant start = OffsetDateTime.of( 2020 , 1 , 23 , 15 , 30 , 0 , 0 , ZoneOffset.UTC ).toInstant();
Instant stop = OffsetDateTime.of( 2020 , 1 , 23 , 15 , 30 , 0 , 0 , ZoneOffset.UTC ).plusWeeks(7 ).toInstant();

时刻与日期

我们的两个Instant 对象都代表一个时刻。目标是数周。周表示天,天表示日历上的某些日期。

所以我们有点不匹配。对于任何给定的时刻,日期在全球范围内因时区而异。法国巴黎午夜过后几分钟是一个新的日期。与此同时,在蒙特利尔魁北克,晚了几个小时,同一时刻仍然是“昨天”,也就是日历上的前一天。所以我们不能直接从一对时刻计算周数。

您必须首先确定您希望在哪个时区感知这些时刻的日历。

Continent/Region 的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用 2-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。

ZoneId z = ZoneId.of( "America/Montreal" ) ; 

ZonedDateTime

将此ZoneId 应用于我们的Instant 对象以调整到时区,从而产生一对ZonedDateTime 对象。

ZonedDateTime startZdt = start.atZone( z ) ;
ZonedDateTime stopZdt = stop.atZone( z ) ;

ChronoUnit.WEEKS

现在我们可以使用ChronoUnit 枚举来计算经过的周数。

长周 = ChronoUnit.WEEKS.between( startZdt , stopZdt );

转储到控制台。

System.out.println( "start.toString() = " + start );
System.out.println( "stop.toString() = " + stop );
System.out.println( "startZdt.toString() = " + startZdt );
System.out.println( "stopZdt.toString() = " + stopZdt );
System.out.println( "weeksCount: " + weeksCount );

看到这个code run live at IdeOne.com

start.toString() = 2020-01-23T15:30:00Z

stop.toString() = 2020-03-12T15:30:00Z

startZdt.toString() = 2020-01-23T10:30-05:00[美国/蒙特利尔]

stopZdt.toString() = 2020-03-12T11:30-04:00[美国/蒙特利尔]

周数:7

三十加分

ThreeTen-Extra 项目为 Java 8 及更高版本中内置的java.time 框架添加了功能。

Weeks

该项目包含一个 Weeks 类来表示周数。它不仅可以计算,还可以在您的代码中用作类型安全的对象。这样的使用还有助于使您的代码自我记录。

您可以通过使用Weeks.between 方法提供一对时间点来实例化。这些时间点可以是实现java.time.temporal.Temporal 的任何内容,包括InstantLocalDateOffsetDateTimeZonedDateTimeYearYearMonth 等。

您的java.util.Date 对象可以轻松转换为Instant 对象,在UTC 时间轴上的时刻,分辨率以纳秒为单位。查看添加到旧日期时间类的新方法。如需从日期到即时,请致电java.util.Date::toInstant

Weeks weeks = Weeks.between( startZdt , stopZdt );

您可以询问周数。

int weeksNumber = weeks.getAmount(); // The number of weeks in this Weeks object.

您还可以做得更多。

生成标准ISO 8601 格式的字符串。 P 标志着开始。 W 表示周数。

PW7


关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

从哪里获得 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可能会在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

【讨论】:

  • 通常我不喜欢投反对票,但出于以下原因在这里这样做:a) 你的代码抛出一个UnsupportedTemporalTypeException。 b) 引入 Threeten-Extra 作为解决方案是愚蠢的,因为 Java-8 已经支持计算经过的周数,请在此处查看@TechTrip 的正确答案,那么仅为此目的添加额外依赖项有什么意义? c) Threeten-Extra 没有“官方”身份。未来对java.time 的增强直接发生在 OpenJDK 上(请参阅 java.time-component 中 Java-9 的所有预定功能)。
  • @MenoHochschild 感谢您的批评。考虑到这些,我修改了我的答案。
  • 好的,在您更正后,我已经撤消了否决票。
【解决方案4】:

使用java.util.Calendar中的日期算法:

public static int getWeeksBetween (Date a, Date b) {

    if (b.before(a)) {
        return -getWeeksBetween(b, a);
    }
    a = resetTime(a);
    b = resetTime(b);

    Calendar cal = new GregorianCalendar();
    cal.setTime(a);
    int weeks = 0;
    while (cal.getTime().before(b)) {
        // add another week
        cal.add(Calendar.WEEK_OF_YEAR, 1);
        weeks++;
    }
    return weeks;
}

public static Date resetTime (Date d) {
    Calendar cal = new GregorianCalendar();
    cal.setTime(d);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}

【讨论】:

  • 如果日期在不同年份,这个功能会起作用吗?
  • 你需要把日期对齐到一周的第一天,否则同一周的不同天会返回1
  • 类似 cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
【解决方案5】:

如果您的要求是开始日期是 2020 年 4 月 3 日,结束日期是 2020 年 4 月 7 日。两个日期相差4天。现在,两个日期之间的周数为 1,您可以在 sn-p 下方使用。

ChronoUnit.WEEKS.between(LocalDate startDate, LocalDate endDate);

但如果您的要求是 2020 年 4 月 3 日在一周内,2020 年 4 月 7 日在另一周内,那么您希望 两个日期之间的周数为 2,您可以使用下面的sn-p。

LocalDate actualStartDate=...
LocalDate actualEndDate=...

LocalDate startDate = actualStartDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY)) 

LocalDate endDate = actualEndDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SATURDAY)) 

long daysBetweenTwoDates = ChronoUnit.DAYS.between(startDate, endDate);
int numberOfWeeks =  (int)Math.ceil(daysBetweenTwoDates/7.0);

在 java 1.8 中测试

【讨论】:

  • 在 JDK11 Base 的项目中测试(正确)
【解决方案6】:
Calendar a = new GregorianCalendar(2002,1,22);
    Calendar b = new GregorianCalendar(2002,1,28);
    System.out.println(a.get(Calendar.WEEK_OF_YEAR));
    System.out.println(b.get(Calendar.WEEK_OF_YEAR)); 
   int weeks = b.get(Calendar.WEEK_OF_YEAR)-a.get(Calendar.WEEK_OF_YEAR);
    System.out.println(weeks);

试试这个一定可以的

    Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.set(2007, 01, 10);
calendar2.set(2007, 07, 01);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
int diffWeeks = (int)diff / (7*24 * 60 * 60 * 1000);

【讨论】:

  • 此方法不适用于不同年份的日期
  • 问题已经是关于如何计算不同年份的周数了。解决方案没有意义!
【解决方案7】:

这是我编写的 2 种方法,它们不基于外部库。
第一种方法是星期一是一周的第一天。
第二种方法是星期日是一周的第一天。

请阅读代码中的 cmets,可以选择返回 2 个日期之间的完整周数,
以及 2 个日期之前和之后剩余天数的分数。

public static int getNumberOfFullWeeks(LocalDate startDate,LocalDate endDate)
{
    int dayBeforeStartOfWeek = 0;
    int daysAfterLastFullWeek = 0;

    if(startDate.getDayOfWeek() != DayOfWeek.MONDAY)
    {
        // get the partial value before loop starting
        dayBeforeStartOfWeek = 7-startDate.getDayOfWeek().getValue() + 1;
    }

    if(endDate.getDayOfWeek() != DayOfWeek.SUNDAY)
    {
        // get the partial value after loop ending
        daysAfterLastFullWeek = endDate.getDayOfWeek().getValue();
    }

    LocalDate d1 = startDate.plusDays(dayBeforeStartOfWeek); // now it is the first day of week;
    LocalDate d2 = endDate.minusDays(daysAfterLastFullWeek); // now it end in the last full week

    // Count how many days there are of full weeks that start on Mon and end in Sun
    // if the startDate and endDate are less than a full week the while loop
    // will not iterate at all because d1 and d2 will be the same date
    LocalDate looper = d1;
    int counter = 1;
    while (looper.isBefore(d2))
    {
        counter++;
        looper = looper.plusDays(1);
    }

    // Counter / 7 will always be an integer that will represents full week
    // because we started to count at Mon and stop counting in Sun
    int fullWeeks = counter / 7;

    System.out.println("Full weeks between dates: "
            + fullWeeks + " Days before the first monday: "
            + dayBeforeStartOfWeek + " "
            + " Days after the last sunday: " + daysAfterLastFullWeek);
    System.out.println(startDate.toString() + " - " + endDate.toString());

    // You can also get a decimal value of the full weeks plus the fraction if the days before
    // and after the full weeks
    float full_weeks_decimal = (float)fullWeeks;
    float fraction = ((float)dayBeforeStartOfWeek + (float)daysAfterLastFullWeek) / 7.0F;
    System.out.println("Full weeks with fraction: " + String.valueOf(fraction + full_weeks_decimal));

    return fullWeeks;
}

public static int getNumberOfFullWeeks_WeekStartAtSunday(LocalDate startDate,LocalDate endDate)
{
    int dayBeforeStartOfWeek = 0;
    int daysAfterLastFullWeek = 0;

    if(startDate.getDayOfWeek() != DayOfWeek.SUNDAY)
    {
        // get the partial value before loop starting
        dayBeforeStartOfWeek = 7-getDayOfWeekBySundayIs0(startDate.getDayOfWeek()) + 1;
    }

    if(endDate.getDayOfWeek() != DayOfWeek.SATURDAY)
    {
        // get the partial value after loop ending
        daysAfterLastFullWeek = 1+getDayOfWeekBySundayIs0(endDate.getDayOfWeek());
    }

    LocalDate d1 = startDate.plusDays(dayBeforeStartOfWeek); // now it is the first day of week;
    LocalDate d2 = endDate.minusDays(daysAfterLastFullWeek); // now it end in the last full week

    // Count how many days there are of full weeks that start on Sun and end in Sat
    // if the startDate and endDate are less than a full week the while loop
    // will not iterate at all because d1 and d2 will be the same date
    LocalDate looper = d1;
    int counter = 1;
    while (looper.isBefore(d2))
    {
        counter++;
        looper = looper.plusDays(1);
    }

    // Counter / 7 will always be an integer that will represents full week
    // because we started to count at Sun and stop counting in Sat
    int fullWeeks = counter / 7;

    System.out.println("Full weeks between dates: "
            + fullWeeks + " Days before the first sunday: "
            + dayBeforeStartOfWeek + " "
            + " Days after the last saturday: " + daysAfterLastFullWeek);
    System.out.println(startDate.toString() + " - " + endDate.toString());

    // You can also get a decimal value of the full weeks plus the fraction if the days before
    // and after the full weeks
    float full_weeks_decimal = (float)fullWeeks;
    float fraction = ((float)dayBeforeStartOfWeek + (float)daysAfterLastFullWeek) / 7.0F;
    System.out.println("Full weeks with fraction: " + String.valueOf(fraction + full_weeks_decimal));

    return fullWeeks;
}

   public static int getDayOfWeekBySundayIs0(DayOfWeek day)
    {
        if(day == DayOfWeek.SUNDAY)
        {
            return 0;
        }
        else
        {
            // NOTE: getValue() is starting to count from 1 and not from 0
            return  day.getValue();
        }
    }

【讨论】:

  • 我同意最好使用内置的 java.time(LocalDateDayOfWeek)。在我看来,您的解决方案显得不必要地复杂。感谢您分享您的代码。
【解决方案8】:

如果您想要确切的整周数,请使用以下方法,其中结束日期是唯一的:

public static long weeksBetween(Date date1, Date date2) {
    return WEEKS.between(date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
        date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
  }

如果你想要这个的 ceil 版本,请在下面使用:

public static long weeksBetween(Date date1, Date date2) {
    long daysBetween = DAYS.between(date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
        date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) + 1;
    return daysBetween / 7 + (daysBetween % 7 == 0 ? 0 : 1);
  }

【讨论】:

  • 尊敬的投反对票的人,请礼貌地添加评论,说明您投反对票的原因。
【解决方案9】:

你可以这样做:

// method header not shown
// example dates:
f = new GregorianCalendar(2009,Calendar.AUGUST,1);
l = new GregorianCalendar(2010,Calendar.SEPTEMBER,1);
DateTime start = new DateTime(f);
DateTime end = new DateTime(l);
// Alternative to above - example dates with joda:
// DateTime start = new DateTime(2009,8,1,0,0,0,0);
// DateTime end = new DateTime(2010,9,1,0,0,0,0);
Interval interval = new Interval(start,end);
int weeksBetween = interval.toPeriod(PeriodType.weeks()).getWeeks();
// return weeksBetween;

这应该给你一个 int 表示两个日期之间的周数。

【讨论】:

  • 如果您使用 nansen 的答案,则不需要上面示例中的 Interval 行。它甚至更好。
【解决方案10】:

Joda Time 以两个日期的持续时间计算周数,在某些情况下这可能不符合我们的要求。我有一个使用 Joda Time 的方法来计算两个日期之间的自然周数。希望它可以帮助你。如果你不使用 Joda Time,你可以用 Calendar 修改代码来做同样的事情。

//Unlike Joda Time Weeks.weeksBetween() that returns whole weeks computed
//from duration, we return natural weeks between two dates based on week of year
public static int weeksBetween(ReadablePartial date1, ReadablePartial date2) {
    int comp = date1.compareTo(date2);
    if (comp == 0) {
        return 0;
    }

    if (comp > 0) {
        ReadablePartial mid = date2;
        date2 = date1;
        date1 = mid;
    }

    int year1 = date1.get(DateTimeFieldType.weekyear());
    int year2 = date2.get(DateTimeFieldType.weekyear());

    if (year1 == year2) {
        return date2.get(DateTimeFieldType.weekOfWeekyear()) - date1.get(DateTimeFieldType.weekOfWeekyear());
    }

    int weeks1 = 0;

    LocalDate lastDay1 = new LocalDate(date1.get(DateTimeFieldType.year()), 12, 31);
    if (lastDay1.getWeekyear() > year1) {
        lastDay1 = lastDay1.minusDays(7);
        weeks1++;
    }

    weeks1 += lastDay1.getWeekOfWeekyear() - date1.get(DateTimeFieldType.weekOfWeekyear());

    int midWeeks = 0;
    for (int i = year1 + 1; i < year2; i++) {
        LocalDate y1 = new LocalDate(i, 1, 1);
        int yearY1 = y1.getWeekyear();
        if (yearY1 < i) {
            y1 = y1.plusDays(7);
            midWeeks++;
        }

        LocalDate y2 = new LocalDate(i, 12, 31);
        int yearY2 = y2.getWeekyear();
        if (yearY2 > i) {
            y2 = y2.minusDays(7);
            midWeeks++;
        }

        midWeeks += y2.getWeekOfWeekyear() - y1.getWeekOfWeekyear();
    }

    int weeks2 = 0;
    LocalDate firstDay2 = new LocalDate(date2.get(DateTimeFieldType.year()), 1, 1);
    if (firstDay2.getWeekyear() < firstDay2.getYear()) {
        firstDay2 = firstDay2.plusDays(7);
        weeks2++;
    }
    weeks2 += date2.get(DateTimeFieldType.weekOfWeekyear()) - firstDay2.getWeekOfWeekyear();

    return weeks1 + midWeeks + weeks2;
}

【讨论】:

    【解决方案11】:
        int startWeek = c1.get(Calendar.WEEK_OF_YEAR);
        int endWeek = c2.get(Calendar.WEEK_OF_YEAR);    
    
        int diff = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
    
        int deltaYears = 0;
        for(int i = 0;i < diff;i++){
            deltaYears += c1.getWeeksInWeekYear();
            c1.add(Calendar.YEAR, 1);        
        }
        diff = (endWeek + deltaYears) - startWeek;
    

    包括年份差异。 这对我有用:)

    【讨论】:

      【解决方案12】:
      private int weeksBetween(Calendar startDate, Calendar endDate) {
          startDate.set(Calendar.HOUR_OF_DAY, 0);
          startDate.set(Calendar.MINUTE, 0);
          startDate.set(Calendar.SECOND, 0);
          int start = (int)TimeUnit.MILLISECONDS.toDays(
              startDate.getTimeInMillis())
              - startDate.get(Calendar.DAY_OF_WEEK);
          int end = (int)TimeUnit.MILLISECONDS.toDays(
              endDate.getTimeInMillis());
          return (end - start) / 7;
      }
      

      如果此方法返回 0,则它们在同一周

      如果此方法返回 1 endDate 是 startDate 之后的一周

      如果此方法返回 -1 endDate 是 startDate 的前一周

      你懂的

      【讨论】:

      • 请不要发帖duplicate answers。相反,请考虑其他可以帮助未来用户找到所需答案的操作,如链接帖子中所述。
      • @Mogsdad 这不是一个重复的答案 这是一个不需要使用 joda-time 的答案(人们可能不想为一个简单的功能下载它)而且这个功能无论如何都可以工作日期是什么。仅当两个答案都在同一年或忽略夏令时之类的事情时,其他陈述的答案才有效
      • 通过“重复”,我并不是说你重复了关于这个问题的答案,而是你已经粘贴了自己的 duplicate from a different question. 如果 questions 相同,它们应该被标记为重复。如果不是,您的答案 应针对具体问题进行调整。或者,链接到另一个答案的 comment 是合适的。
      【解决方案13】:

      不使用 JodaTime,我能够准确计算 2 个日历之间的周数(考虑闰年等)

      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")
          }
      }
      

      【讨论】:

        【解决方案14】:

        简单的方法

          Calendar cal1 = new GregorianCalendar();
            Calendar cal2 = new GregorianCalendar();
            cal1.set(2014, 3, 3);
            cal2.set(2015, 3, 6);
        
            weekscount.setText("weeks= "+ ( (cal2.getTime().getTime() - cal1.getTime().getTime()) / (1000 * 60 * 60 * 24))/7);
        

        【讨论】:

          【解决方案15】:

          这是查找两个日期之间的周数的简单方法。

          SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
          String classStartData = "31 01 2021";
          String classEndData = "08 03 2021";
          
          Date dateClassStart = myFormat.parse(classStartData);
          Date dateClassEnd = myFormat.parse(classEndData);
          
          long differenceWeek = dateClassEnd.getTime() - dateClassStart.getTime();
          int programLength = (int)(TimeUnit.DAYS.convert(differenceWeek, TimeUnit.MILLISECONDS)/7);
          System.out.println("Class length in weeks: " +programLength);
          

          【讨论】:

            【解决方案16】:

            看看下面的文章:Java - calculate the difference between two dates

            daysBetween 方法将允许您获取日期之间的天数。然后你可以简单地除以 7 得到完整的周数。

            【讨论】:

            • 错了 - 周五和周一之间是 3 天,但是是一周。
            【解决方案17】:
                    Calendar date1 = Calendar.getInstance();
                    Calendar date2 = Calendar.getInstance();
            
                    date1.clear();
                    date1.set(datePicker1.getYear(), datePicker1.getMonth(),
                            datePicker1.getDayOfMonth());
                    date2.clear();
                    date2.set(datePicker2.getYear(), datePicker2.getMonth(),
                            datePicker2.getDayOfMonth());
            
                    long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
            
                    float dayCount = (float) diff / (24 * 60 * 60 * 1000);
            
                    int week = (dayCount / 7) ;
            

            希望对你有帮助

            【讨论】:

            • 这段代码假设每一天的持续时间都以毫秒为单位,但由于夏令时和闰秒,情况并非如此,因此会导致错误的结果。
            【解决方案18】:

            public int diffInWeeks(Date start, Date end) { long diffSeconds = (end.getTime() - start.getTime())/1000; return (int)diffSeconds/(60 * 60 * 24 * 7); }

            【讨论】:

            • 当间隔包括不完全是 24 小时的天数时,这将给出不正确的结果,例如由于夏令时或闰秒。
            猜你喜欢
            • 1970-01-01
            • 2017-11-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多