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 GregorianCalend er 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
GregorianCalend ar 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 GregorianCalend ar(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.Field Position;
import java.text.Simpl eDateFormat;
import java.util.Grego rianCalendar;
public class WeekTest {
private GregorianCalend ar calendar;
public WeekTest(Gregor ianCalendar calendar) {
this.calendar = calendar;
this.calendar.s etFirstDayOfWee k(GregorianCale ndar.MONDAY);
this.calendar.s etMinimalDaysIn FirstWeek(4);
System.out.prin tln("\nStarting as: " +
calendar.getTim e().toString()) ;
}
public WeekTest(int year, int month, int date) {
this(new GregorianCalend ar(year, month, date, 1, 1));
}
public WeekTest() {
this(new GregorianCalend ar());
}
public String getWeek(){
String format = "yyyyww";
return doFormat(format , calendar);
}
public String getStartDate(){
calendar.set(Gr egorianCalendar .DAY_OF_WEEK,
GregorianCalend ar.MONDAY);
calendar.get(Gr egorianCalendar .MILLISECOND);
System.out.prin t("Week Start: " +
calendar.getTim e().toString() + " = ");
String format = "yyyyMMdd";
return doFormat(format , calendar);
}
public String getEndDate(){
calendar.set(Gr egorianCalendar .DAY_OF_WEEK,
GregorianCalend ar.SUNDAY);
System.out.prin t("Week End: " +
calendar.getTim e().toString() + " = ");
String format = "yyyyMMdd";
return doFormat(format , calendar);
}
private String doFormat(String format, GregorianCalend ar gc){
SimpleDateForma t sdf = new SimpleDateForma t(format);
FieldPosition fpos = new FieldPosition(0 );
StringBuffer b = new StringBuffer();
StringBuffer sb = sdf.format(gc.g etTime(), b, fpos);
return sb.toString();
}
public static void main (String[] args) {
WeekTest wsw = new WeekTest(2002,
GregorianCalend ar.OCTOBER, 6);
System.out.prin tln("Week: " + wsw.getWeek());
System.out.prin tln(wsw.getStar tDate());
System.out.prin tln(wsw.getEndD ate());
WeekTest wsw2 = new WeekTest();
System.out.prin tln("Week: " + wsw2.getWeek()) ;
System.out.prin tln(wsw2.getSta rtDate());
System.out.prin tln(wsw2.getEnd Date());
System.exit(0);
}
}
-end code--------------------------------------