Java examples for java.util:Week
Given the date from the specified GregorianCalendar instance, returns the date of monday in the same week.
/**//w w w. j a va 2 s . c om * Copyright (c) 2010 Martin Geisse * * This file is distributed under the terms of the MIT license. */ import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main{ /** * Given the date from the specified {@link GregorianCalendar} instance, returns * the date of monday in the same week. Monday is considered the first day of week * by this method. Note that the returned day may be in the previous month and even * year. * * The time part of the returned object is unspecified. * @param anchorDate the date to start from * @return the date of monday in the same week */ public static GregorianCalendar getMondayFromDate( GregorianCalendar anchorDate) { int dayOfMonth = anchorDate.get(Calendar.DAY_OF_MONTH); Month month = Month.from(anchorDate); int year = anchorDate.get(Calendar.YEAR); return getMondayFromDate(year, month, dayOfMonth); } /** * Given the specified year, month and day of month, returns the date of monday * in the same week. Monday is considered the first day of week by this method. * Note that the returned day may be in the previous month and even year. * * The time part of the returned object is unspecified. * * @param year the year to start from * @param month the month to start from * @param dayOfMonth the day of month to start from * @return the date of monday in the same week */ public static GregorianCalendar getMondayFromDate(int year, Month month, int dayOfMonth) { GregorianCalendar c = new GregorianCalendar(); setTimeToMidnight(c); c.set(Calendar.YEAR, year); c.set(Calendar.MONTH, month.getGregorianCalendarValue()); c.set(Calendar.DAY_OF_MONTH, dayOfMonth); DayOfWeek argumentDayOfWeek = DayOfWeek.from(c); c.add(Calendar.DAY_OF_MONTH, -(argumentDayOfWeek.ordinal() - DayOfWeek.MONDAY.ordinal())); return c; } /** * Sets the time fields (24-hour, minute, second, millisecond) of the specified * {@link GregorianCalendar} instance to 0 so it subsequently represents midnight * of the same day as before. * @param c the instance to modify */ public static void setTimeToMidnight(GregorianCalendar c) { c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); } }