Hi, I have the following java code to get the date of a specific week day:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.YEAR, 2010);
cal.set(Calendar.WEEK_OF_YEAR, 37); //week 37 of year 2010
cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
System.out.println("date="+sdf.format(cal.getTime()));
When I put this code in a main(String[] args)
method, like the following:
import java.util.*;
import java.lang.*;
import java.text.SimpleDateFormat;
public class test{
public static void main(String[] args){
/** get dates from a known week ID **/
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.YEAR, 2010);
cal.set(Calendar.WEEK_OF_YEAR, 37);
cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
System.out.println("date="+sdf.format(cal.getTime()));
}
}
and run it, I get the correct result which is date=09/09/2010
. There is no problem.
HOWEVER...
When I put this code in a function of a Class, like the following:
Public Class MyService{
MyService(){}
...
...
public String getDateOfWeekDay(int weekId, int year, int weekDay){
//weekId = 37; year=2010; weekDay = Calendar.THURSDAY
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, weekId);
cal.set(Calendar.DAY_OF_WEEK, weekDay);
//I am developing android app. so I use Log to printout
logPrinter.println("date="+sdf.format(cal.getTime()));
return sdf.format(cal.getTime());
}
}
in another class MainClass, MainClass will invoke this service function like following:
Public Class MainClass{
MyService myService = new MyService();
myService.getDateOfWeekDay(37,2010,Calendar.THURSDAY);
}
But the result returned is always the date of the current week's thursday (date=14/10/2010), not the Thursday of the week which I specified (week 37, year 2010, Thursday). WHY???? I use exactly the same java code to get the date of the specific week day, only used it in different ways, why the result is different???? I can not understand this...Anybody can explain to me??