I have data such as September2021W5, in which W5 is the week number of the month September2021. How do i get daterange i.e start date and end date of that particular week. Thanks in advance for any help provided.
CodePudding user response:
Build a DateTimeFormatter that uses a default day of week as needed (start of week, e.g. Monday).
Example:
var format = new DateTimeFormatterBuilder()
.appendPattern("MMMMuuuu'W'W") // or use corresponding appends
.parseDefaulting(ChronoField.DAY_OF_WEEK, DayOfWeek.MONDAY.getValue())
.toFormatter()
.withLocale(Locale.US);
var date = LocalDate.parse("September2021W5", format);
same can be done for the end of the week, or just adding 6 days to previous result (date.plusDays(6))
MMMM is for month of year, full form
uuuu year
'W' for literal W
W for week of month
Using Locale.UK so the month gets parsed for that locale, use the one needed for the given input - to use the default system Locale, use Locale.getDefault().
CodePudding user response:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
public class HelloWorld
{
public static void main(String []args)
{
// your input date
LocalDate localDate = LocalDate.of(2022, 9, 30);
// ensure week 5
LocalDate week = localDate.with(ChronoField.ALIGNED_WEEK_OF_MONTH, 5);
// get localDate for first and last day
LocalDate start = week.with(DayOfWeek.MONDAY);
LocalDate end = start.plusDays(6);
System.out.println(start " - " end);
}
}
