cg_news wrote:
In short, what I am trying to do is, based on a date, calculate the week
of year (as described in ISO 8601), then calculate the first and last date
in this week period and return them in the format CCYYMMDD. Sounds easy
enough, right??
I am attempting to accomplish this by creating a GregorianCalender which
will get me the week of year. Then by changing the day of week to 1 (start
of week) i'm trying the get the first day of the week, and day_of_week = 7
should get me the last. Maybe?
I think I may have successfully done this by using an instance of the
GregorianCalendar with the no argument constructor, which appears to
default to the current system date/time. However, when I attempt to do the
same with the GregorianCalendar(int year, int month, int date)
constructor, it does not work. It seems that my attemps to set the
DAY_OF_WEEK value have no effect?
Some code samples below,
Thanks for any help you can offer...
Carl.
Doh!
Code:
-start code--------------------------------------
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
public class WeekTest {
private GregorianCalendar calendar;
public WeekTest(GregorianCalendar calendar) {
this.calendar = calendar;
this.calendar.setFirstDayOfWeek(GregorianCalendar. MONDAY);
this.calendar.setMinimalDaysInFirstWeek(4);
System.out.println("\nStarting as: " +
calendar.getTime().toString());
}
public WeekTest(int year, int month, int date) {
this(new GregorianCalendar(year, month, date, 1, 1));
}
public WeekTest() {
this(new GregorianCalendar());
}
public String getWeek(){
String format = "yyyyww";
return doFormat(format, calendar);
}
public String getStartDate(){
calendar.set(GregorianCalendar.DAY_OF_WEEK,
GregorianCalendar.MONDAY);
calendar.get(GregorianCalendar.MILLISECOND);
System.out.print("Week Start: " +
calendar.getTime().toString() + " = ");
String format = "yyyyMMdd";
return doFormat(format, calendar);
}
public String getEndDate(){
calendar.set(GregorianCalendar.DAY_OF_WEEK,
GregorianCalendar.SUNDAY);
System.out.print("Week End: " +
calendar.getTime().toString() + " = ");
String format = "yyyyMMdd";
return doFormat(format, calendar);
}
private String doFormat(String format, GregorianCalendar gc){
SimpleDateFormat sdf = new SimpleDateFormat(format);
FieldPosition fpos = new FieldPosition(0);
StringBuffer b = new StringBuffer();
StringBuffer sb = sdf.format(gc.getTime(), b, fpos);
return sb.toString();
}
public static void main (String[] args) {
WeekTest wsw = new WeekTest(2002,
GregorianCalendar.OCTOBER, 6);
System.out.println("Week: " + wsw.getWeek());
System.out.println(wsw.getStartDate());
System.out.println(wsw.getEndDate());
WeekTest wsw2 = new WeekTest();
System.out.println("Week: " + wsw2.getWeek());
System.out.println(wsw2.getStartDate());
System.out.println(wsw2.getEndDate());
System.exit(0);
}
}
-end code--------------------------------------