2013-05-13 327 views
5

我有一個小問題,我正在開發一個應用程序,並且需要將星期幾的開始日從星期一改爲另一星期四(星期四,星期六)。這是可能的android, 我需要計算開始到星期和它的結束知道日期。 (以星期四開始的星期四爲例)Android日曆:更改一週的開始日期

注意:我只是Android開發的初學者。 這是我的代碼 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()); 

使用上面的代碼即時獲得結果,但星期一作爲周的明星。

注:因爲與變化一週指數的變化是開始

+1

「我需要改變一週的開始日期「 - 在*什麼*? 'CalendarView'?還有別的嗎? – CommonsWare 2013-05-13 12:51:50

+0

發佈您的代碼。 – Blackbelt 2013-05-13 12:55:29

+0

立即檢查我的帖子,對不起,可能是壞的英文 – 2013-05-13 12:59:58

回答

20

日曆天有值1-7天星期日至星期六我不能添加一天的結果。 getFirstDayOfWeek根據使用的Locale返回其中一個值(通常爲星期一或星期日)。 Calendar.getInstance根據手機的設置使用默認Locale,在您的情況下,星期一爲一週中的第一天。

一個解決辦法是使用其他Locale

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

將返回1,這是價值Calendar.SUNDAY

其他的解決辦法是使用一週值的選擇一天是

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

問題是,Calendar正在使用其在中的第一個星期內的值。例如:

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 

如果你不想使用Locale或需要其他日期作爲一週的第一天,它可能是最好來計算自己的一週的開始。

0
public int getWeekdayOfMonth(int year, int month){ 
    Calendar cal = Calendar.getInstance(); 
    cal.set(year, month-1, 1); 
    dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1; 
    return dayOfWeek; 
} 

weekday = getWeekdayOfMonth();

int day = (weekday - firstweek) < 0 ? (7 - (firstweek - weekday)) : (weekday - firstweek); 

「firstweek」是指你的起始日要

那麼你可以計算出你應該show.If你有簡單的方法,第一天是什麼,請告訴我們。 THKS

3
GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 0); 

改變值0 - 從週一開始 日新月異的值爲1 - 從星期日開始 日等..

希望這有助於和工程:)

+0

工作正常,謝謝+1 – 2018-02-14 09:04:34