Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

java - Android Calendar: Changing the start day of week

i have a little problem, i'm developing an application, and i need to change the start day of the week from monday to another one (thursday, of saturday). is this possible in android, i need to calculate the start to week and its end knowing the date. (the week starts ano thursday as example)

Note: i'm just a beginner in android development. here is my code SimpleDateFormat dateformate = new SimpleDateFormat("dd/MM");

// get today and clear time of day
Calendar cal = Calendar.getInstance();

// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
cal.add(Calendar.DAY_OF_YEAR, 7*(WeekIndex-1));
result = dateformate.format(cal.getTime());

cal.add(Calendar.DAY_OF_YEAR, 6 );

result=result+" - " + dateformate.format(cal.getTime());

using the above code im getting the result but with monday as the star of week.

Note: i can't add day to the result because week index changes with the changing of it's start

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Calendar days have values 1-7 for days Sunday-Saturday. getFirstDayOfWeek returns one of this values (usually of Monday or Sunday) depending on used Locale. Calendar.getInstance uses default Locale depening on phone's settings, which in your case has Monday as first day of the week.

One solution would be to use other Locale:

Calendar.getInstance(Locale.US).getFirstDayOfWeek()

would return 1, which is value of Calendar.SUNDAY

Other solution would be to use chosen day of week value like

cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);

Problem is, Calendar is using its inner first day of the week value in set as well. Example:

Calendar mondayFirst = Calendar.getInstance(Locale.GERMANY); //Locale that has Monday as first day of week
mondayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
log(DateUtils.formatDateTime(context, mondayFirst.getTimeInMillis(), 0));
//prints "May 19" when runned on May 13

Calendar sundayFirst = Calendar.getInstance(Locale.US); //Locale that has Sunday as first day of week
sundayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
log(DateUtils.formatDateTime(context, sundayFirst.getTimeInMillis(), 0));
//prints "May 12" when runned on May 13

If you don't want to use Locale or you need other day as the first day of the week, it may be best to calculate start of the week on your own.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...