I have a small program that displays the current week from todays date, like this:
GregorianCalendar gc = new GregorianCalendar();
int day = 0;
gc.add(Calend
Java 1.8 provides you with some new classes in package java.time
:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.IsoFields;
ZonedDateTime now = ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
System.out.printf("Week %d%n", now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR));
Most legacy calendars can easily be converted to java.time.ZonedDateTime
/ java.time.Instant
by interoperability methods, in your particular case GregorianCalendar.toZonedDateTime()
.
WeekFields
This method that I created works for me in Java 8 and later, using WeekFields, DateTimeFormatter, LocalDate, and TemporalField.
Don't forget to format your date properly based on your use case!
public int getWeekNum(String input) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yy"); // Define formatting pattern to match your input string.
LocalDate date = LocalDate.parse(input, formatter); // Parse string into a `LocalDate` object.
WeekFields wf = WeekFields.of(Locale.getDefault()) ; // Use week fields appropriate to your locale. People in different places define a week and week-number differently, such as starting on a Monday or a Sunday, and so on.
TemporalField weekNum = wf.weekOfWeekBasedYear(); // Represent the idea of this locale’s definition of week number as a `TemporalField`.
int week = Integer.parseInt(String.format("%02d",date.get(weekNum))); // Using that locale’s definition of week number, determine the week-number for this particular `LocalDate` value.
return week;
}