Aujourd'hui, nous sommes le 2014-04-06 (dimanche).
Le résultat obtenu en utilisant le code ci-dessous est:
Start Date = 2014-04-07
End Date = 2014-04-13
Voici le résultat que j'aimerais obtenir à la place:
Start Date = 2014-03-31
End Date = 2014-04-06
Comment puis-je atteindre cet objectif?
C'est le code que j'ai complété jusqu'à présent:
// Get calendar set to current date and time
Calendar c = GregorianCalendar.getInstance();
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";
startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());
System.out.println("Start Date = " + startDate);
System.out.println("End Date = " + endDate);
En utilisant Java 8 et en gardant le même principe qu'auparavant (le premier jour de la semaine dépend de votre Locale
), vous devriez envisager d'utiliser les éléments suivants:
DayOfWeek
pour une Locale
spécifiquefinal DayOfWeek firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
final DayOfWeek lastDayOfWeek = DayOfWeek.of(((firstDayOfWeek.getValue() + 5) % DayOfWeek.values().length) + 1);
LocalDate.now(/* tz */).with(TemporalAdjusters.previousOrSame(firstDayOfWeek)); // first day
LocalDate.now(/* tz */).with(TemporalAdjusters.nextOrSame(lastDayOfWeek)); // last day
Considérons la class
suivante:
private static class ThisLocalizedWeek {
// Try and always specify the time zone you're working with
private final static ZoneId TZ = ZoneId.of("Pacific/Auckland");
private final Locale locale;
private final DayOfWeek firstDayOfWeek;
private final DayOfWeek lastDayOfWeek;
public ThisLocalizedWeek(final Locale locale) {
this.locale = locale;
this.firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
this.lastDayOfWeek = DayOfWeek.of(((this.firstDayOfWeek.getValue() + 5) % DayOfWeek.values().length) + 1);
}
public LocalDate getFirstDay() {
return LocalDate.now(TZ).with(TemporalAdjusters.previousOrSame(this.firstDayOfWeek));
}
public LocalDate getLastDay() {
return LocalDate.now(TZ).with(TemporalAdjusters.nextOrSame(this.lastDayOfWeek));
}
@Override
public String toString() {
return String.format( "The %s week starts on %s and ends on %s",
this.locale.getDisplayName(),
this.firstDayOfWeek,
this.lastDayOfWeek);
}
}
Nous pouvons démontrer son utilisation comme suit:
final ThisLocalizedWeek usWeek = new ThisLocalizedWeek(Locale.US);
System.out.println(usWeek);
// The English (United States) week starts on SUNDAY and ends on SATURDAY
System.out.println(usWeek.getFirstDay()); // 2018-01-14
System.out.println(usWeek.getLastDay()); // 2018-01-20
final ThisLocalizedWeek frenchWeek = new ThisLocalizedWeek(Locale.FRANCE);
System.out.println(frenchWeek);
// The French (France) week starts on MONDAY and ends on SUNDAY
System.out.println(frenchWeek.getFirstDay()); // 2018-01-15
System.out.println(frenchWeek.getLastDay()); // 2018-01-21
Utilisez simplement:
c.setFirstDayOfWeek(Calendar.MONDAY);
Pour le moment, votre premier jour de la semaine est défini sur Calendar.SUNDAY
. Ceci est un paramètre qui dépend de votre Locale
.
Ainsi, une meilleure alternative serait d’initialiser votre Calendar
en spécifiant la Locale
qui vous intéresse.
Par exemple:
Calendar c = GregorianCalendar.getInstance(Locale.US);
... vous donnerait votre courant sortie, tandis que:
Calendar c = GregorianCalendar.getInstance(Locale.FRANCE);
... vous donnerait votre attendu sortie.
Eh bien, on dirait que tu as eu ta réponse. Voici un add-on utilisant Java.time dans Java 8 et versions ultérieures. (Voir Tutoriel )
import Java.time.DayOfWeek;
import Java.time.LocalDate;
public class MondaySunday
{
public static void main(String[] args)
{
LocalDate today = LocalDate.now();
// Go backward to get Monday
LocalDate monday = today;
while (monday.getDayOfWeek() != DayOfWeek.MONDAY)
{
monday = monday.minusDays(1);
}
// Go forward to get Sunday
LocalDate sunday = today;
while (sunday.getDayOfWeek() != DayOfWeek.SUNDAY)
{
sunday = sunday.plusDays(1);
}
System.out.println("Today: " + today);
System.out.println("Monday of the Week: " + monday);
System.out.println("Sunday of the Week: " + sunday);
}
}
Une autre façon de le faire, en utilisant les ajusteurs temporels .
import Java.time.LocalDate;
import static Java.time.DayOfWeek.MONDAY;
import static Java.time.DayOfWeek.SUNDAY;
import static Java.time.temporal.TemporalAdjusters.nextOrSame;
import static Java.time.temporal.TemporalAdjusters.previousOrSame;
public class MondaySunday
{
public static void main(String[] args)
{
LocalDate today = LocalDate.now();
LocalDate monday = today.with(previousOrSame(MONDAY));
LocalDate sunday = today.with(nextOrSame(SUNDAY));
System.out.println("Today: " + today);
System.out.println("Monday of the Week: " + monday);
System.out.println("Sunday of the Week: " + sunday);
}
}
C'est ce que j'ai fait pour obtenir les dates de début et de fin de la semaine en cours.
public static Date getWeekStartDate() {
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.add(Calendar.DATE, -1);
}
return calendar.getTime();
}
public static Date getWeekEndDate() {
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.add(Calendar.DATE, 1);
}
calendar.add(Calendar.DATE, -1);
return calendar.getTime();
}
J'ai utilisé la méthode ci-dessous pour vérifier si une date donnée tombe dans la semaine en cours
public boolean isDateInCurrentWeek(Date date)
{
Date currentWeekStart, currentWeekEnd;
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setFirstDayOfWeek(Calendar.MONDAY);
while(currentCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY)
{
currentCalendar.add(Calendar.DATE,-1);//go one day before
}
currentWeekStart = currentCalendar.getTime();
currentCalendar.add(Calendar.DATE, 6); //add 6 days after Monday
currentWeekEnd = currentCalendar.getTime();
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.setFirstDayOfWeek(Calendar.MONDAY);
targetCalendar.setTime(date);
Calendar tempCal = Calendar.getInstance();
tempCal.setTime(currentWeekStart);
boolean result = false;
while(!(tempCal.getTime().after(currentWeekEnd)))
{
if(tempCal.get(Calendar.DAY_OF_YEAR)==targetCalendar.get(Calendar.DAY_OF_YEAR))
{
result=true;
break;
}
tempCal.add(Calendar.DATE,1);//advance date by 1
}
return result;
}
Calendar privCalendar = Calendar.getInstance();
Date fdow, ldow;
int dayofWeek = privCalendar.get ( Calendar.DAY_OF_WEEK );
Date fdow, ldow;
if( dayofWeek == Calendar.SUNDAY ) {
privCalendar.add ( Calendar.DATE, -1 * (dayofWeek -
Calendar.MONDAY ) - 7 );
fdow = privCalendar.getTime();
privCalendar.add( Calendar.DATE, 6 );
ldow = privCalendar.getTime();
} else {
privCalendar.add ( Calendar.DATE, -1 * (dayofWeek -
Calendar.MONDAY ) );
fdow = privCalendar.getTime();
privCalendar.add( Calendar.DATE, 6 );
ldow = privCalendar.getTime();
}