Week start and end on Android

I wonder how I could calculate the start and end days of the current week? I found that this is not implemented in standard android lib files or libs like date4j.

If there is a simple and easy way to implement this? Or do I need to use the bike again?

Thanks.

+3
source share
6 answers

Maybe MonthDisplayHelper can help you.

Good luck

+4
source

It does not take much code to do this with date4j. Example of calculating the first day of the week:

private void firstDayOfThisWeek(){ DateTime today = DateTime.today(TimeZone.getDefault()); DateTime firstDayThisWeek = today; //start value int todaysWeekday = today.getWeekDay(); int SUNDAY = 1; if(todaysWeekday > SUNDAY){ int numDaysFromSunday = todaysWeekday - SUNDAY; firstDayThisWeek = today.minusDays(numDaysFromSunday); } System.out.println("The first day of this week is : " + firstDayThisWeek); } 

The foregoing follows that Sunday is the beginning of the week. Some jurisdictions do not apply this agreement, so you will need to change the code for such cases.

+4
source

Try java.util.Calendar.getFirstDayOfWeek () ... then it's easy to calculate the last day of the week: http://developer.android.com/reference/java/util/Calendar.html#getFirstDayOfWeek ()

+1
source

This kind of working with a date is often easier with the Joda-Time 2.3 library.

Taken from this answer to a similar question.

 LocalDate now = new LocalDate(); System.out.println( now.withDayOfWeek(DateTimeConstants.MONDAY) ); System.out.println( now.withDayOfWeek(DateTimeConstants.SUNDAY) ); 

You can call isBefore / isAfter and minusWeeks / plusWeeks to get past / future values.

+1
source

It worked for me ...

 Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); cal.set(Calendar.DAY_OF_WEEK, cal.MONDAY); String firstWkDay = String.valueOf(cal.getTime()); //cal.set(Calendar.DAY_OF_WEEK, cal.SUNDAY); cal.add(Calendar.DAY_OF_WEEK, 6); String lastWkDay = String.valueOf(cal.getTime()); 

On the last day of the week, you can use cal.set(Calendar.DAY_OF_WEEK, cal.SUNDAY); but it returns the previous sunday on some devices

+1
source

This is what I used to get the date:

  Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); c.setFirstDayOfWeek(Calendar.MONDAY); startOfWeek = c.getTime(); 
0
source

All Articles