問題描述
我有一個小問題,我正在開發一個應用程序,我需要將一周的開始日期從星期一更改為另一個(星期四、星期六).這在android中可能嗎,我需要計算一周的開始和知道日期的結束.(例如一周從星期四開始)
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 開發的初學者.這是我的代碼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());
使用上面的代碼我得到了結果,但星期一是一周的明星.
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
推薦答案
周日到周六的日歷日值是 1-7.getFirstDayOfWeek
根據使用的 Locale
返回其中一個值(通常是星期一或星期日).Calendar.getInstance
使用默認的 Locale
取決于手機的設置,在您的情況下,星期一是一周的第一天.
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
中使用其內部一周的第一天值.示例:
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
或者您需要其他日期作為一周的第一天,最好自己計算一周的開始時間.
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.
這篇關于Android 日歷:更改一周的開始日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!