Skip to content

Instantly share code, notes, and snippets.

@WardBenjamin
Created December 14, 2018 18:21
Show Gist options
  • Save WardBenjamin/e91e57bfc0614bc2b0d4e084875ffe04 to your computer and use it in GitHub Desktop.
Save WardBenjamin/e91e57bfc0614bc2b0d4e084875ffe04 to your computer and use it in GitHub Desktop.
Calculate the number of weeks "between" two dates, inclusive.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Main {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date start = dateFormat.parse("2019-01-01"),
end = dateFormat.parse("2019-01-21");
int weeks1 = option1(start, end);
int weeks2 = option2(start, end);
int weeks3 = option3(start, end);
System.out.println("Weeks:\n\tOption 1: " + weeks1 + "\n\tOption 2: " + weeks2 + "\n\tOption 3: " + weeks3);
}
public static int option1(Date start, Date end) {
Calendar cal = new GregorianCalendar();
cal.setTime(start);
int weeks = 0;
while (cal.getTime().before(end)) {
cal.add(Calendar.WEEK_OF_YEAR, 1);
weeks++;
}
return weeks;
}
public static int option2(Date start, Date end) {
Calendar a = new GregorianCalendar();
Calendar b = new GregorianCalendar();
a.setTime(start);
b.setTime(end);
return b.get(Calendar.WEEK_OF_YEAR) - a.get(Calendar.WEEK_OF_YEAR);
}
public static int option3(Date start, Date end) {
Date firstOfWeek = Date.from(start.toInstant().atZone(ZoneId.of("America/New_York")).toLocalDate().with(
TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY)
).atStartOfDay(ZoneId.systemDefault()).toInstant());
Date lastOfWeek = Date.from(end.toInstant().atZone(ZoneId.of("America/New_York")).toLocalDate().with(
TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)
).atStartOfDay(ZoneId.systemDefault()).toInstant());
return option1(firstOfWeek, lastOfWeek);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment