通过在java中传递开始日期和结束日期来获取给定日期的周数

时间:2016-06-04 02:23:04

标签: java datetime

我正在尝试获取开始日期和结束日期之间的给定日期的周数。 以下是我过去常用的代码,但它只能工作4周。

我需要它才能使它工作数周。

public static int getWeekNO( Timestamp startTime,Timestamp endTime , Timestamp dateTime) throws RuntimeException {

        String formatted = null;
        Timestamp currentTimestamp;
        int weekNumber = 0;

        logger.debug("startTime"+startTime);
        logger.debug("endTime"+endTime);
        logger.debug("dateTime"+dateTime);
        try {
            String formatDateFirst =  "";
            String formatDateSecond = "";
            String formatDateThird = "";
            String formatDateFourth = "";
            String givenDateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dateTime);
            String startDateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime);
            String endDateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime);
            logger.debug("givenDateString"+givenDateString);
            logger.debug("startDateString"+startDateString);
            logger.debug("endDateString"+endDateString);


            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Calendar c = Calendar.getInstance();
            Date givenDate = sdf.parse(givenDateString);
            Date startDate = sdf.parse(startDateString);
            Date endDate = sdf.parse(endDateString);

            logger.debug("givenDate"+givenDate);
            logger.debug("startDate"+startDate);
            logger.debug("endDate"+endDate);

            c.setTime(sdf.parse(startDateString));

            c.add(Calendar.DAY_OF_MONTH, 6); // number of days to add
            formatDateFirst = sdf.format(c.getTime());
            Date firstWeekDate = (Date) sdf.parse(formatDateFirst);
            logger.debug("endDate"+firstWeekDate);

            c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
            formatDateSecond = sdf.format(c.getTime());
            Date secondWeekDate = (Date) sdf.parse(formatDateSecond);
            logger.debug("endDate"+secondWeekDate);

            c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
            formatDateThird = sdf.format(c.getTime());
            Date thirdWeekDate = (Date) sdf.parse(formatDateThird);
            logger.debug("endDate"+thirdWeekDate);

            c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
            formatDateFourth = sdf.format(c.getTime());
            Date fourthWeekDate = (Date) sdf.parse(formatDateFourth);
            logger.debug("endDate"+fourthWeekDate);


            if (givenDate.compareTo(firstWeekDate) <= 0) {
                weekNumber = 1;
            } else if (givenDate.compareTo(secondWeekDate) <= 0
                    && givenDate.compareTo(firstWeekDate) > 0) {
                weekNumber = 2;
                } else if (givenDate.compareTo(thirdWeekDate) <= 0
                    && givenDate.compareTo(secondWeekDate) > 0) {
                    weekNumber = 3;
            }else if (givenDate.compareTo(fourthWeekDate) <= 0
                    && givenDate.compareTo(thirdWeekDate) > 0) {
                    weekNumber = 4;
            }else{
                logger.debug("Not a Valid Date");
            }

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return weekNumber;
    } 

示例:

  start Timestamp: 09/04/2016 00:00:00,End Timestamp: 28/06/2016 00:00:00. Given Timestamp : 15/05/2016 00:00:00

so here:week 1:09/04/2016 - 15/04/2016
        week 2:16/04/2016 - 22/04/2016
        week 3:23/04/2016 - 29/04/2016
        week 4:30/04/2016 - 06/05/2016
        week 5:07/05/2016 - 13/05/2016
        week 6:14/05/2016 - 20/05/2016 -- my given timestamp falls here
        week 7:21/05/2016 - 27/05/2016
        week 8:28/05/2016 - 03/06/2016

so now my output for week no should be week:6 

这里我使用java 1.7所以我无法使用 - import java.time.LocalDateTime; import java.time.temporal.ChronoUnit;

我怎么能实现,请帮助我。

2 个答案:

答案 0 :(得分:0)

    public static int getWeekNO(Timestamp startTime, Timestamp endTime, Timestamp dateTime) {
      if (dateTime.compareTo(startTime) < 0 || dateTime.compareTo(endTime) > 0) {
        System.out.println("Not a Valid Date");
        return -1;
      }
      return (int) ((dateTime.getTime() - startTime.getTime() - 1) / (1000L * 3600 * 24 * 7)) + 1;
    }

修改

根据要求,更新了答案,

public static int getWeekNO(Timestamp startTime, Timestamp endTime, Timestamp dateTime) {
  if (dateTime.compareTo(startTime) < 0 || dateTime.compareTo(endTime) > 0) {
    System.out.println("Not a Valid Date");
    return -1;
  }
  int dayDiff = (int) ((dateTime.getTime() - startTime.getTime()) / (1000L * 3600 * 24)) + 1;
  int week = dayDiff / 7;
  return dayDiff % 7 == 0 ? week : week + 1;
}

注意:注意Date / Timestamp的构造函数,

  Timestamp startTime = new Timestamp(2016, 5, 30, 0, 0, 0, 0);
  Timestamp dateTime = new Timestamp(2016, 6, 6, 0, 0, 0, 0);

这个构造函数月份从0开始。所以上面的代码是比较2016-4-30到2016-5-6。这只有一个星期。

答案 1 :(得分:0)

使用java.time

不要将java.sql.Timestamp用于业务逻辑。该类仅用于与数据库交换数据。甚至这个目的现在也被java.time类所取代。对于Java 7,请使用下面的项目符号中列出的java.time的后端。

java.util.Datejava.util.Calendarjava.text.SimpleTextFormat等棘手的旧日期时间类现在是legacy,取代了java.time类。

DayOfWeek

指定您认为是一周开始的星期几。使用DayOfWeek枚举对象。顺便提一下,标准ISO 8601 week定义从星期一开始。

DayOfWeek dowStart = DayOfWeek.MONDAY ;

LocalDate

LocalDate类表示没有时间且没有时区的仅限日期的值。

指定开始/停止日期。

LocalDate start = LocalDate.parse( 2016 , 4 , 9 ) ; 
LocalDate stop = LocalDate.parse( 2016 , 6 , 28 ) ;
LocalDate first = start.with( TemporalAdjusters.previousOrSame( dowStart ) ) ;

List<LocalDate> dates = new ArrayList<>() ;
LocalDate ld = first ; // Initialize for loop.
while( ld.isBefore( stop ) ) {  // While the local date is before the stopping point.
    dates.add( ld ) ;
    // Prepare for next loop.
    ld = ld.plusWeeks( 1 ) ;
}

现在以您选择的任何方式报告您的工作日开始日期。

int i = 0 ;  // Initialize for loop.
for( LocalDate ld : dates ) {
    i ++ ;
    String output = "Week # " + i + ":" + ld + " - " + ld.plusDays( 6 ) ;
    …
}

关于java.time

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

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

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore