Java Week Calculate weekNumber()

Here you can find the source of weekNumber()

Description

week Number

License

LGPL

Return

the week number offset from INITIAL_YEAR for this week

Declaration

public static int weekNumber() 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.util.*;

public class Main {
    public static final int INITIAL_YEAR = 2000;
    /** First day of work within a week */
    public static final int FIRST_DAY_OF_WORK = Calendar.MONDAY;

    /**/*from   ww w. j a v a 2  s. co m*/
       @return the week number offset from INITIAL_YEAR for this week
     */
    public static int weekNumber() {
        return weekNumber(new GregorianCalendar());
    }

    /**
       @return the week number offset from INITIAL_YEAR for the given date
     */
    public static int weekNumber(GregorianCalendar cal) {
        int yearNum = cal.get(Calendar.YEAR) - INITIAL_YEAR;
        int weekNum = cal.get(Calendar.WEEK_OF_YEAR);
        if (cal.before(weekStart(cal))) {
            // This can happen since we allow a different FIRST_DAY_OF_WORK, eg. if that's Monday then Sunday is part of the week before
            weekNum = weekNum - 1;
        }
        return (yearNum * 52) + weekNum;
    }

    /**
       @return the week number offset from INITIAL_YEAR for the given date
     */
    public static int weekNumber(Date date) {
        GregorianCalendar newCal = new GregorianCalendar();
        newCal.setTime(date);
        return weekNumber(newCal);
    }

    /**
       @return the starting moment of the current week
     */
    public static GregorianCalendar weekStart() {
        return weekStart(new GregorianCalendar());
    }

    /**
       @return the starting moment of the week containing the given date
       Note that it is set to the FIRST_DAY_OF_WORK.
     */
    public static GregorianCalendar weekStart(GregorianCalendar cal) {
        GregorianCalendar newCal = (GregorianCalendar) cal.clone();
        newCal.set(Calendar.DAY_OF_WEEK, FIRST_DAY_OF_WORK);
        newCal.set(Calendar.HOUR_OF_DAY, 0);
        newCal.set(Calendar.MINUTE, 0);
        newCal.set(Calendar.SECOND, 0);
        newCal.set(Calendar.MILLISECOND, 0);
        return newCal;
    }
}

Related

  1. nextWeek(long date)
  2. plusHour(Date date, int plusWeek)
  3. startOfWeek(Date datum)
  4. weekCal(int weekNumber)
  5. weekCount(Date start, Date end)
  6. weeksInYear(int year)
  7. weekStart()