問題描述
我有一個(gè)小問題,我正在開發(fā)一個(gè)應(yīng)用程序,我需要將一周的開始日期從星期一更改為另一個(gè)(星期四、星期六).這在android中可能嗎,我需要計(jì)算一周的開始和知道日期的結(jié)束.(例如一周從星期四開始)
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)
注意:我只是 android 開發(fā)的初學(xué)者.這是我的代碼SimpleDateFormat dateformate = new SimpleDateFormat("dd/MM");
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());
使用上面的代碼我得到了結(jié)果,但星期一是一周的明星.
using the above code im getting the result but with monday as the star of week.
注意:我無法在結(jié)果中添加日期,因?yàn)橹芩饕龝S著開始時(shí)間的變化而變化
Note: i can't add day to the result because week index changes with the changing of it's start
推薦答案
周日到周六的日歷日值是 1-7.getFirstDayOfWeek
根據(jù)使用的 Locale
返回其中一個(gè)值(通常是星期一或星期日).Calendar.getInstance
使用默認(rèn)的 Locale
取決于手機(jī)的設(shè)置,在您的情況下,星期一是一周的第一天.
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.
一種解決方案是使用其他Locale
:
One solution would be to use other Locale
:
Calendar.getInstance(Locale.US).getFirstDayOfWeek()
將返回 1
,即 Calendar.SUNDAY
其他解決方案是使用選定的星期幾值,例如
Other solution would be to use chosen day of week value like
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
問題是,Calendar
也在 set
中使用其內(nèi)部一周的第一天值.示例:
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
如果您不想使用 Locale
或者您需要其他日期作為一周的第一天,最好自己計(jì)算一周的開始時(shí)間.
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.
這篇關(guān)于Android 日歷:更改一周的開始日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!