Skip to content

Instantly share code, notes, and snippets.

@brainsatwork
Created April 13, 2011 21:10
Show Gist options
  • Save brainsatwork/918426 to your computer and use it in GitHub Desktop.
Save brainsatwork/918426 to your computer and use it in GitHub Desktop.
Calculating calendar weeks in GWT
public static String CwIso (Date inputDate) {
String output = "Input: " + inputDate.toString() + "\r";
Date thisThursday = new Date(inputDate.getYear(), inputDate.getMonth(), inputDate.getDate() - weekday(inputDate) + 4);
Date firstOfJan = new Date(thisThursday.getYear(), 0, 1);
Date firstThursdayOfYear = new Date(thisThursday.getYear(), 0, 1);
while(weekday(firstThursdayOfYear) != 4){
firstThursdayOfYear.setDate(firstThursdayOfYear.getDate() + 1);
}
Date firstMondayOfYear = new Date(firstThursdayOfYear.getYear(), 0, firstThursdayOfYear.getDate() - 3);
Long diff = thisThursday.getTime() - firstMondayOfYear.getTime();
Long cw = (thisThursday.getTime() - firstMondayOfYear.getTime())/1000/60/60/24/7 + 1;
output += "This Thursday: " + df.format(thisThursday) + "\r";
output += "First of January: " + df.format(firstOfJan) + "\r";
output += "Diff: " + diff + "\r";
output += "KW: " + cw + "\r";
return output;
}
public static Long calendarWeekIso (Date inputDate) {
Date thisThursday = new Date(inputDate.getYear(), inputDate.getMonth(), inputDate.getDate() - weekday(inputDate) + 4);
Date firstOfJan = new Date(thisThursday.getYear(), 0, 1);
Date firstThursdayOfYear = new Date(thisThursday.getYear(), 0, 1);
while(weekday(firstThursdayOfYear) != 4){
firstThursdayOfYear.setDate(firstThursdayOfYear.getDate() + 1);
}
Date firstMondayOfYear = new Date(firstThursdayOfYear.getYear(), 0, firstThursdayOfYear.getDate() - 3);
Long cw = (thisThursday.getTime() - firstMondayOfYear.getTime())/1000/60/60/24/7 + 1;
return cw;
}
public static Integer weekday (Date date){
int weekday = date.getDay();
if(weekday == 0){
weekday = 7;
}
return weekday;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment