简体   繁体   中英

Android - determine start and end date of week

I have written simple code for getting start and end date of a week. It goes like

Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year);

calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
start = new DateTime(calendar.getTime());

calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
end = new DateTime(calendar.getTime());

start and end are DateTime from joda time . week and year are parameters.

The problem is that when I debug this piece of code, it's working. When not debugging, the start and end is set for current week. To be clear, I have to debug line by line not to only run app in debug mode. Sometimes the year is set but start and end dime are the same. I have no idea what could cause that.

Actually, I could figure out what was the problem, but if someone is looking for a really easy way to get start and end date of any week in any year you can use JodaTime .

DateTime start = new DateTime().withWeekOfWeekyear(week).withYear(year).withDayOfWeek(1); //1 - monday

DateTime end = new DateTime().withWeekOfWeekyear(week).withYear(year).withDayOfWeek(7); //7 - sunday

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