Ebenezer Isaac
Ebenezer Isaac

Reputation: 802

How to get successive week number and year in java?

I am storing some data referenced with the week number. Now, I have two button to request for data. One for previous week and the another for the next week.And data for current week is fetched by default

I just finished making exceptions for the year end that I learned that there is week 53 too next year (2020). Now it breaks everytime there is a week 53. (It just skips week 53s)

Obviously, there must be a better way of doing this.. I just kept adding exceptions and following is the code I ended up with. I am a noob, so please bear with the ugly logic.

LocalDate wks, mon, tue, wed, thu, fri, sat, wke;
try {
    week = Integer.parseInt(request.getParameter("week"));
    year = Integer.parseInt(request.getParameter("year"));
} catch (NumberFormatException e) {
    week = getWeek();
    year = getCurrYear();
    flag = 1;
}
LocalDate date = LocalDate.now()
.withYear(year) // year
.with(WeekFields.ISO.weekOfWeekBasedYear(), week) // week of year
.with(WeekFields.ISO.dayOfWeek(), 7);
wks = date.plusDays(-7);
if ((date + "").substring(0, 4).equals((wks + "").substring(0, 4))) {
} else if (flag == 1) {
    year++;
}
date = LocalDate.now()
.withYear(year) // year
.with(WeekFields.ISO.weekOfWeekBasedYear(), week) // week of year
.with(WeekFields.ISO.dayOfWeek(), 7);
wks = date.plusDays(-7);
mon = wks.plusDays(1);
tue = wks.plusDays(2);
wed = wks.plusDays(3);
thu = wks.plusDays(4);
fri = wks.plusDays(5);
sat = wks.plusDays(6);
wke = date;
System.out.println(week + " " + year);
heading = "<div class='row'>"
        + "<form action=\"";
if (week == 1) {
    heading += "javascript:setContent('/getData?week=52&year=" + (year - 1) + "')\" >";
} else {
    heading += "javascript:setContent('getData?week=" + (week - 1) + "&year=" + (year) + "')\" >";
}
heading += "<button type='submit'>Previous</button></form><form action=\"";
if (week == 52) {
    heading += "javascript:setContent('getData?week=1&year=" + (year + 1) + "')\" >";
} else {
    heading += "javascript:setContent('getData?week=" + (week + 1) + "&year=" + (year) + "')\" >";
}
heading += "<button type='submit'Next</button></form>";
out.print(heading);

function: getWeek()

public static int getWeek() {
        java.util.Date date = new java.util.Date();
        SimpleDateFormat ft = new SimpleDateFormat("w");
        return (Integer.parseInt(ft.format(date)));
    }

function: getCurrYear() {

public static int getCurrYear() {
         Date date = new Date();
         return (date.getYear() + 1900);
    }

I have to print the dates of the days in the week, that's why variables of monday to saturday.

I just want a function like below

function int[] getWeekYear(){
    return [prev week,prev week's year,current week,current year,next week,next week's year];
}

Upvotes: 3

Views: 499

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338276

tl;dr

YearWeek
.now( 
    ZoneId.of( "Asia/Tokyo" ) 
)
.minusWeeks( 1 ) 
.getWeek()         // Returns an `int` in range of 1-52 or 1-53, the week number within a year. 

Details

Never use either of the two Date classes. They are terrible, and are now legacy. They were supplanted years ago by the modern java.time classes defined in JSR 310.

The Answer by Renato is correct.

YearWeek

Furthermore, if your definition of a week is the standard ISO 8601 definition (week starts on a Monday, week # 1 contains first Thursday of calendar-year), then add the ThreeTen-Extra library to your project. This library has classes extending the functionality of java.time. In particular, you get the YearWeek class.

Get current week. This requires a time zone. For any given moment the date varies around the globe by time zone.

ZoneId z = ZoneId.of( "Africa/Tunis" );
YearWeek currentWeek = YearWeek.now( z ) ;

To get prior or next week, simply call the plus or minus methods.

YearWeek priorWeek = currentWeek.minusWeeks( 1 ) ;
YearWeek followingWeek = currentWeek.plusWeeks( 1 ) ;

If you want a date from a week, call atDay and pass a day-of-week from the DayOfWeek enum.

LocalDate localDate = priorWeek.atDay( DayOfWeek.MONDAY ) ;

You can interrogate for the week’s number and its year number (week-based-year that is).

int weekNumber = priorWeek.getWeek() ;
int weekBasedYearNumber = priorWeek.getYear() ; 

Upvotes: 2

Renato
Renato

Reputation: 2157

The package java.time will give you a lot of satisfaction:

LocalDate.now().get(WeekFields.ISO.weekOfWeekBasedYear())

This will return the week of the year (executed now returns 52), but the whole package contains everything you need, you have just to explore.

Upvotes: 0

Related Questions