简体   繁体   中英

Get week number of given date by passing start and end date in java

I am trying to get week number of given date that lies between start and end date. Below is the code i have used to get but it works only for 4 weeks.

I need it to make it to work for any number of weeks.

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;
    } 

Example:

  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 

Here i am using java 1.7 so i am not able to use -- import java.time.LocalDateTime; import java.time.temporal.ChronoUnit;

How could i achieve, this please help me on this.

    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;
    }

As request, updated the answer,

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;
}

Notice: Be careful about the constructor of Date/Timestamp,

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

This constructor the month starts with 0. So the above code is comparing 2016-4-30 to 2016-5-6. It's only one week.

Using java.time

Do not use java.sql.Timestamp for business logic. That class is only for exchanging data with your database. And even that purpose is now supplanted by the java.time classes. For Java 7, use the back-port of java.time listed in bullets below.

The troublesome old date-time classes such as java.util.Date , java.util.Calendar , and java.text.SimpleTextFormat are now legacy , supplanted by the java.time classes.

DayOfWeek

Specify the day-of-week you consider to be the beginning of a week. Use a DayOfWeek enum object. By the ways, standard ISO 8601 week definition begins with Monday.

DayOfWeek dowStart = DayOfWeek.MONDAY ;

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

Specify your start/stop dates.

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

Now report on your week-starting dates in any manner you choose.

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

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM