The number of "week of year" returned from a Date is wrong.
This is my code:
Calendar c = Calendar.getInstance();
c.setTime(my_date);
int num_week = c.get(Calendar.WEEK_OF_YEAR);
If my_date (type Date) is 01/01/2011, I supposed that "week of year" is 1. But it returned 52.
I try to test with these methods but I don't obtain anything:
c.setFirstDayOfWeek(6);
c.setMinimalDaysInFirstWeek(1)
If It's interesting, I'm from Spain, and our week begin on Monday.
Have I to do anything for obtain right results?
Thanks!
This may be Android/Harmony-specific. For example, this works for me with desktop 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
}
}
Can you confirm that the exact same code (modulo logging options) logs 52 twice on Android?
Here you can view the reference by oracle
https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html
And I have placed a quick solution to find the week count of current day. You can alter and optimize as your way. Also set according to your convenient GMT value
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;
}
At the end just call the method getWeeksOfMonth();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.