在Android中错误的“一年中的一周”

时间:2011-09-01 16:08:54

标签: android date calendar

从日期返回的“一年中的一周”数量是错误的。

这是我的代码:

Calendar c = Calendar.getInstance();
c.setTime(my_date);
int num_week = c.get(Calendar.WEEK_OF_YEAR);

如果my_date(类型日期)是01/01/2011,我认为“一年中的一周”是1.但是它返回了52。

我尝试使用这些方法测试,但我没有获得任何东西:

c.setFirstDayOfWeek(6);
c.setMinimalDaysInFirstWeek(1)

如果它很有意思,我来自西班牙,我们的星期一星期一开始。

我有什么需要做的才能获得正确的结果吗?

谢谢!

2 个答案:

答案 0 :(得分:3)

这可能是特定于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次吗?

答案 1 :(得分:0)

在这里您可以通过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();