Util.java Source code

Java tutorial

Introduction

Here is the source code for Util.java

Source

/*
Copyright (C) 2008-2009 Dmitry Gusev <dmitry.gusev@gmail.com>
    
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
 */

import java.util.Calendar;
import java.util.Date;

public class Util {
    public static Date getMonday(Date today) {
        Calendar cal = Calendar.getInstance();

        cal.setTime(today);

        int dow = cal.get(Calendar.DAY_OF_WEEK);

        while (dow != Calendar.MONDAY) {
            int date = cal.get(Calendar.DATE);

            if (date == 1) {
                int month = cal.get(Calendar.MONTH);

                if (month == Calendar.JANUARY) {
                    month = Calendar.DECEMBER;

                    cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) - 1);
                } else {
                    month--;
                }

                cal.set(Calendar.MONTH, month);

                date = getMonthLastDate(month, cal.get(Calendar.YEAR));
            } else {
                date--;
            }

            cal.set(Calendar.DATE, date);

            dow = cal.get(Calendar.DAY_OF_WEEK);
        }

        return cal.getTime();
    }

    private static int getMonthLastDate(int month, int year) {
        switch (month) {
        case Calendar.JANUARY:
        case Calendar.MARCH:
        case Calendar.MAY:
        case Calendar.JULY:
        case Calendar.AUGUST:
        case Calendar.OCTOBER:
        case Calendar.DECEMBER:
            return 31;

        case Calendar.APRIL:
        case Calendar.JUNE:
        case Calendar.SEPTEMBER:
        case Calendar.NOVEMBER:
            return 30;

        default: //  Calendar.FEBRUARY
            return year % 4 == 0 ? 29 : 28;
        }
    }
}