Get StartWeek, EndWeek in calendar java

public class JavaClass {

    public static void main(String[] args) {

        Calendar mCalendar = Calendar.getInstance();
        //Case 1: 02/11/2017
        mCalendar.set(Calendar.YEAR, 2017);
        mCalendar.set(Calendar.MONTH, Calendar.NOVEMBER);
        mCalendar.set(Calendar.DAY_OF_MONTH, 2);
        getStartWeekEndWeek(mCalendar);

        //Case 2: 04/11/2017
        mCalendar.set(Calendar.YEAR, 2017);
        mCalendar.set(Calendar.MONTH, Calendar.NOVEMBER);
        mCalendar.set(Calendar.DAY_OF_MONTH, 4);
        getStartWeekEndWeek(mCalendar);

        //Case 3: 04/11/2017
        mCalendar.set(Calendar.YEAR, 2017);
        mCalendar.set(Calendar.MONTH, Calendar.NOVEMBER);
        mCalendar.set(Calendar.DAY_OF_MONTH, 5);
        getStartWeekEndWeek(mCalendar);

    }

    public static void getStartWeekEndWeek(Calendar calendar){
        Calendar first = (Calendar) calendar.clone();
        first.add(Calendar.DAY_OF_WEEK,
                first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
        // and add six days to the end date
        Calendar last = (Calendar) first.clone();
        last.add(Calendar.DAY_OF_YEAR, 6);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("Input: " +df.format(calendar.getTime()));
        System.out.println("Start: " + df.format(first.getTime()) + " -> " +
                df.format(last.getTime()));
        System.out.println("-----------");
    }
}

Nguyễn Linh

Chia sẻ để cùng tiến bộ...