Here you can find the source of getDayofWeekForContainedDate(Date dt, DayOfWeek dow)
Parameter | Description |
---|---|
dt | a parameter |
dow | a parameter |
Parameter | Description |
---|---|
Exception | an exception |
public static Date getDayofWeekForContainedDate(Date dt, DayOfWeek dow) throws Exception
//package com.java2s; //License from project: Open Source License import java.time.*; import java.time.temporal.TemporalAdjusters; import java.util.Date; public class Main { /**/*from w w w. j a va 2s. c o m*/ * Find the day of week within the week that the dt is part of. * * @param dt * @param dow * @return * @throws Exception */ public static Date getDayofWeekForContainedDate(Date dt, DayOfWeek dow) throws Exception { LocalDate dtLocalDate = dateToSystemLocalDate(dt); LocalDateTime dtLocalDateTime = dtLocalDate.atStartOfDay(); dtLocalDate = dtLocalDateTime.toLocalDate(); Date retDate; if (isDayOfWeek(dtLocalDate, dow)) { retDate = localDateToSystemAdjustedStartOfDayDate(dtLocalDate); } else { int dtVal = dtLocalDateTime.getDayOfWeek().getValue(); int dowVal = dow.getValue(); LocalDate tempLocalDate; if (dowVal > dtVal) { tempLocalDate = dtLocalDate.with(TemporalAdjusters.next(dow)); } else { tempLocalDate = dtLocalDate.with(TemporalAdjusters.previous(dow)); } retDate = localDateToSystemAdjustedStartOfDayDate(tempLocalDate); } return retDate; } /** * Takes a java.util.Date and turns it into a LocalDate based on the * systems default timezone. * * @param d * @return * @throws Exception */ public static LocalDate dateToSystemLocalDate(Date d) throws Exception { return d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } /** * Check the LocalDate given to see if it is the DayOfWeek given * * @param d * @param dow */ public static boolean isDayOfWeek(LocalDate d, DayOfWeek dow) throws Exception { if (d.getDayOfWeek().compareTo(dow) == 0) { return true; } else { return false; } } /** * Adjusts a LocalDate to Midnight of the say day (start of day). * * @param d * @return * @throws Exception */ public static Date localDateToSystemAdjustedStartOfDayDate(LocalDate d) throws Exception { LocalDateTime ldt = d.atStartOfDay(); return getSystemDefaultDate(ldt); } /** * Get local system Date from LocalDateTime * * @param ldt * @return * @throws Exception */ public static Date getSystemDefaultDate(LocalDateTime ldt) throws Exception { return Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant()); } }