从Date返回的"年份中的第几周"错误。
这是我的代码:
Calendar c = Calendar.getInstance();
c.setTime(my_date);
int num_week = c.get(Calendar.WEEK_OF_YEAR);
如果my_date (type Date)是01/01/2011,我假设"一年中的星期"是1。但它返回52。
我试着用这些方法测试,但我没有得到任何东西:
c.setFirstDayOfWeek(6);
c.setMinimalDaysInFirstWeek(1)
有趣的是,我来自西班牙,我们的一周从星期一开始。
我要做什么才能得到正确的结果吗?
谢谢!
这可能是Android/harmony特有的。例如,这对我的桌面Java有效:
import java.util.*;
public class Test {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(2011, 0, 1, 0, 0, 0);
System.out.println(calendar.get(Calendar.WEEK_OF_YEAR)); // Prints 52
calendar.setMinimalDaysInFirstWeek(1);
System.out.println(calendar.get(Calendar.WEEK_OF_YEAR)); // Prints 1
}
}
你能确认完全相同的代码(模记录选项)在Android上记录52两次吗?
在这里您可以查看oracle的引用
https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html并且我已经放置了一个快速解决方案来查找当前的周数。您可以按照自己的方式进行更改和优化。也可以根据您方便的GMT值设置
public static int getWeeksOfMonth() {
DATESTATUS = false;
VALUESTATUS = false;
int weekCount;
WEEK_OF_MONTH= -1;
// get the supported ids for GMT+04:00 (Pacific Standard Time)
String[] ids = getAvailableIDs(4 * 60 * 60 * 1000);
// if no ids were returned, something is wrong. get out.
if (ids.length == 0)
return WEEK_OF_MONTH;
// create a Pacific Standard Time time zone
SimpleTimeZone pdt = new SimpleTimeZone(4 * 60 * 60 * 1000, ids[0]);
// create a GregorianCalendar with the Pacific Daylight time zone
// and the current date and time
Calendar calendar = new GregorianCalendar(pdt);
Date trialTime = new Date();
calendar.setTime(trialTime);
weekCount = calendar.get(Calendar.WEEK_OF_YEAR);
return recursiveWeekCountCheck(calendar, weekCount);
}
private static int recursiveWeekCountCheck(Calendar calendar, int weekCount) {
if (calendar.get(Calendar.MONTH) == Calendar.DECEMBER && weekCount == 1) {
DATESTATUS = true;
calendar.add(Calendar.DAY_OF_MONTH, -1);
weekCount = calendar.get(Calendar.WEEK_OF_YEAR);
recursiveWeekCountCheck(calendar, weekCount);
}
if (!VALUESTATUS){
VALUESTATUS = true;
if (DATESTATUS) {
weekCount++;
WEEK_OF_MONTH = weekCount;
} else {
WEEK_OF_MONTH = weekCount;
}
}
return WEEK_OF_MONTH;
}
最后调用getWeeksOfMonth()方法;