Example usage for java.util Calendar DAY_OF_WEEK

List of usage examples for java.util Calendar DAY_OF_WEEK

Introduction

In this page you can find the example usage for java.util Calendar DAY_OF_WEEK.

Prototype

int DAY_OF_WEEK

To view the source code for java.util Calendar DAY_OF_WEEK.

Click Source Link

Document

Field number for get and set indicating the day of the week.

Usage

From source file:com.ericsson.deviceaccess.adaptor.ruleengine.device.Rule.java

public boolean checkWeekDay() {
    Calendar date = Calendar.getInstance();
    int day = date.get(Calendar.DAY_OF_WEEK);
    return weekDaysBool[day - 1];
}

From source file:br.msf.commons.util.AbstractDateUtils.java

public static boolean isBusinessDay(final Object date, final Collection<? extends Object> holidays) {
    if (date == null) {
        return false;
    }//www .  j  a  v  a  2  s .  c o m
    int dayOfWeek = castToCalendar(date).get(Calendar.DAY_OF_WEEK);
    return dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY && !isHoliday(date, holidays);
}

From source file:com.alkacon.opencms.calendar.CmsCalendarMonthBean.java

/**
 * Builds the HTML output to create a basic calendar month overview.<p>
 * //  w w  w .ja  v  a  2 s .c  o m
 * This method serves as a simple example to create a basic html calendar monthly view.<p>
 * 
 * @param year the year of the month to display
 * @param month the month to display 
 * @param calendarLocale the Locale for the calendar to determine the start day of the weeks
 * @param showNavigation if true, navigation links to switch the month are created, otherwise not
 * @return the HTML output to create a basic calendar month overview
 */
public String buildCalendarMonth(int year, int month, Locale calendarLocale, boolean showNavigation) {

    StringBuffer result = new StringBuffer(1024);

    Map dates = getMonthDaysMatrix(year, month, calendarLocale);
    Map monthEntries = getEntriesForMonth(year, month);

    // calculate the start day of the week
    Calendar calendar = new GregorianCalendar(calendarLocale);
    int weekStart = calendar.getFirstDayOfWeek();
    // store current calendar date
    Calendar currentCalendar = (Calendar) calendar.clone();

    // init the date format symbols
    DateFormatSymbols calendarSymbols = new DateFormatSymbols(calendarLocale);

    // open the table
    result.append("<table class=\"");
    result.append(getStyle().getStyleTable());
    result.append("\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n");

    // create the calendar navigation row
    result.append(buildMonthNavigation(year, month, currentCalendar, calendarLocale, showNavigation));

    // create the week day row
    result.append("<tr>\n");
    int currWeekDay = weekStart;
    for (int i = 1; i <= 7; i++) {

        result.append("\t<td class=\"");
        result.append(getStyle().getStyleWeekdays());
        result.append("\">");
        result.append(calendarSymbols.getShortWeekdays()[currWeekDay]);
        result.append("</td>\n");
        // check if we are at end of week
        if (currWeekDay == Calendar.SATURDAY) {
            currWeekDay = 0;
        }

        currWeekDay++;
    }
    result.append("</tr>\n");

    // now create the entry rows
    result.append("<tr>\n");

    // iterate the index entries of the matrix
    Iterator i = dates.keySet().iterator();
    while (i.hasNext()) {
        Integer index = (Integer) i.next();
        result.append("\t<td class=\"");
        Calendar currDay = (Calendar) dates.get(index);
        if (currDay != null) {
            // current index represents a day, create day output
            String styleDayCell = getStyle().getStyleDay();
            if (isCurrentDay(currentCalendar, currDay)) {
                // for the current day, use another cell style
                styleDayCell = getStyle().getStyleDayCurrent();
            }
            // get entries for the day
            List dayEntries = (List) monthEntries.get(currDay.getTime());
            if (dayEntries.size() > 0) {
                // current day has calendar entries
                int weekdayStatus = 0;
                int holidayEntries = 0;
                int commonEntries = dayEntries.size();
                StringBuffer dayText = new StringBuffer(128);
                // check all entries for special weekday status entries
                for (int k = 0; k < commonEntries; k++) {
                    CmsCalendarEntry entry = (CmsCalendarEntry) dayEntries.get(k);
                    int entryWeekdayStatus = entry.getEntryData().getWeekdayStatus();
                    if (entryWeekdayStatus > 0) {
                        // entry is a special weekday
                        holidayEntries++;
                        // append special day info to title info
                        dayText.append(entry.getEntryData().getTitle());
                        dayText.append(" - ");
                        if (entryWeekdayStatus > weekdayStatus) {
                            // increase the status of the weekday
                            weekdayStatus = entryWeekdayStatus;
                        }
                    }
                }
                // calculate the count of common calendar entries
                commonEntries = commonEntries - holidayEntries;
                // determine the CSS class to use
                String dayStyle = getWeekdayStyle(currDay.get(Calendar.DAY_OF_WEEK), weekdayStatus);
                result.append(styleDayCell);
                result.append("\" title=\"");
                result.append(dayText);
                // check the number of common entries and generate output of entry count
                if (commonEntries <= 0) {
                    // no entry found
                    result.append(getMessages().key("calendar.entries.count.none"));
                } else if (commonEntries == 1) {
                    // one entry found
                    result.append(getMessages().key("calendar.entries.count.one"));
                } else {
                    // more than one entry found
                    result.append(getMessages().key("calendar.entries.count.more",
                            new String[] { String.valueOf(commonEntries) }));
                }
                result.append("\">");
                if (commonEntries > 0) {
                    // common entries present, create link to the overview page 
                    result.append("<a href=\"");
                    result.append(createLink(currDay, m_viewUri, true, -1));
                    result.append("\" class=\"");
                    result.append(getStyle().getStyleDayEntryLink());
                    result.append("\">");
                }
                result.append("<span class=\"");
                result.append(dayStyle);
                result.append("\">");
                result.append(currDay.get(Calendar.DAY_OF_MONTH));
                result.append("</span>");
                if (commonEntries > 0) {
                    // common entries present, close link
                    result.append("</a>");
                }
            } else {
                // current day has no entries
                result.append(styleDayCell);
                result.append("\" title=\"");
                result.append(getMessages().key("calendar.entries.count.none"));
                result.append("\">");
                result.append("<span class=\"");
                result.append(getWeekdayStyle(currDay.get(Calendar.DAY_OF_WEEK),
                        I_CmsCalendarEntryData.WEEKDAYSTATUS_WORKDAY));
                result.append("\">");
                result.append(currDay.get(Calendar.DAY_OF_MONTH));
                result.append("</span>");
            }
        } else {
            // this is an empty cell
            result.append(getStyle().getStyleDayEmpty());
            result.append("\">");
        }
        result.append("</td>\n");
        if ((index.intValue() % 7) == 0) {
            // append closing row tag
            result.append("</tr>\n");
            if (i.hasNext()) {
                // open next row if more elements are present
                result.append("<tr>\n");
            }
        }
    }

    // close the table
    result.append("</table>");
    return result.toString();
}

From source file:it.dbCleaner.PurgeTest.java

/**
 * SONAR-7175//from   w w  w.  j  av a  2s. co m
 */
@Test
public void keep_latest_snapshot() {
    // Keep all snapshots from last 4 weeks
    setServerProperty(orchestrator, "sonar.dbcleaner.weeksBeforeKeepingOnlyOneSnapshotByWeek", "4");

    Date oneWeekAgo = addDays(new Date(), -7);

    // Execute an analysis wednesday last week
    Calendar lastWednesday = Calendar.getInstance();
    lastWednesday.setTime(oneWeekAgo);
    lastWednesday.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
    String lastWednesdayFormatted = formatDate(lastWednesday.getTime());
    runProjectAnalysis(orchestrator, PROJECT_SAMPLE_PATH, "sonar.projectDate", lastWednesdayFormatted);

    // Execute an analysis thursday last week
    Calendar lastThursday = Calendar.getInstance();
    lastThursday.setTime(oneWeekAgo);
    lastThursday.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
    String lastThursdayFormatted = formatDate(lastThursday.getTime());
    runProjectAnalysis(orchestrator, PROJECT_SAMPLE_PATH, "sonar.projectDate", lastThursdayFormatted);

    // Now only keep 1 snapshot per week
    setServerProperty(orchestrator, "sonar.dbcleaner.weeksBeforeKeepingOnlyOneSnapshotByWeek", "0");

    // Execute an analysis today to execute the purge of previous weeks snapshots
    runProjectAnalysis(orchestrator, PROJECT_SAMPLE_PATH);

    // Check that only analysis from last thursday is kept (as it's the last one from previous week)
    WsMeasures.SearchHistoryResponse response = newAdminWsClient(orchestrator).measures()
            .searchHistory(SearchHistoryRequest.builder().setComponent(PROJECT_KEY)
                    .setMetrics(singletonList("ncloc")).build());
    assertThat(response.getMeasuresCount()).isEqualTo(1);
    assertThat(response.getMeasuresList().get(0).getHistoryList()).extracting(HistoryValue::getDate)
            .doesNotContain(lastWednesdayFormatted, lastThursdayFormatted);
}

From source file:net.kw.shrdlu.grtgtfs.Activities.RiderAlertsActivity.java

/**
 * Get the latest twitter info. Some of this copied from http://www.vogella.com/articles/AndroidJSON/article.html
 *//*  w  ww . j  a v  a  2 s  .c  om*/
ArrayList<String[]> readTwitterFeed() {
    final StringBuilder builder = new StringBuilder();
    final HttpClient client = new DefaultHttpClient();
    final HttpGet httpGet = new HttpGet(TwitterURL + TwitterQry);
    httpGet.setHeader("Authorization", "Bearer " + AccessToken);

    try {
        final HttpResponse response = client.execute(httpGet);

        final StatusLine statusLine = response.getStatusLine();
        final int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            final HttpEntity entity = response.getEntity();
            final InputStream content = entity.getContent();
            final BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
            content.close();

            // Result is an array of tweets
            final JSONArray arr = (JSONArray) new JSONTokener(builder.toString()).nextValue();

            final ArrayList<String[]> tweets = new ArrayList<>();

            // Need to grok dates of form "created_at": "Thu, 15 Nov 2012 18:27:17 +0000"
            final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy");
            dateFormat.setLenient(true);

            for (int i = 0; i < arr.length(); i++) {
                final String text = arr.getJSONObject(i).get("text").toString();
                String tweettime = arr.getJSONObject(i).get("created_at").toString();

                // Extract & reformat the date
                Date created;
                final GregorianCalendar cal = new GregorianCalendar();
                try {
                    created = dateFormat.parse(tweettime);
                    cal.setTime(created);
                    String day, mon;

                    day = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
                    mon = cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());

                    tweettime = String.format("%s %02d:%02d - %s %d", day, cal.get(Calendar.HOUR_OF_DAY),
                            cal.get(Calendar.MINUTE), mon, cal.get(Calendar.DAY_OF_MONTH));

                } catch (final Exception e) {
                    Log.d(TAG, "Exception: " + e.getMessage() + ", parsing tweet date `" + tweettime + "'");
                    tweettime = "--:--";
                }

                tweets.add(new String[] { tweettime, text });
            }

            return tweets;

        } else {
            Log.d(TAG, "Failed to download twitter info");
        }
    } catch (final ClientProtocolException e) {
        Log.d(TAG, "ClientProtocolException: " + e.getMessage() + ", Failed to download twitter info");
    } catch (final IOException e) {
        Log.d(TAG, "IOException: " + e.getMessage() + ", Failed to download twitter info");
    } catch (final Exception e) {
        Log.d(TAG, "Exception: " + e.getMessage() + ", Failed to download twitter info");
    }

    return null;
}

From source file:com.glaf.core.util.DateUtils.java

/**
 * //from w  ww  .  j  av a2  s  .  com
 * 
 * @param startDate
 * @param endDate
 * @return
 */
public static int getWorkingDay(Calendar startDate, Calendar endDate) {
    int result = -1;
    if (startDate.after(endDate)) {
        java.util.Calendar swap = startDate;
        startDate = endDate;
        endDate = swap;
    }

    int charge_start_date = 0;// ???
    int charge_end_date = 0;// ????
    // ??
    int stmp;
    int etmp;
    stmp = 7 - startDate.get(Calendar.DAY_OF_WEEK);
    etmp = 7 - endDate.get(Calendar.DAY_OF_WEEK);
    if (stmp != 0 && stmp != 6) {// ???0
        charge_start_date = stmp - 1;
    }
    if (etmp != 0 && etmp != 6) {// ????0
        charge_end_date = etmp - 1;
    }

    result = (getDaysBetween(getNextMonday(startDate), getNextMonday(endDate)) / 7) * 5 + charge_start_date
            - charge_end_date;
    return result;
}

From source file:com.chortitzer.web.bas.controller.GranosBean.java

/**
 * @param selectedRango the selectedRango to set
 *//*from   w  w w.j  a v  a2s .c om*/
public void setSelectedRango(int selectedRango) {
    try {
        this.selectedRango = selectedRango;
        if (selectedRango != 0) {
            setFechaHasta(new Date());
            switch (selectedRango) {
            case 1:
                setFechaDesde(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH));
                break;
            case 2:
                fechaDesde = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
                setFechaDesde(DateUtils.addDays(fechaDesde, -1));
                fechaHasta = DateUtils.addDays(fechaDesde, 1);
                setFechaHasta(DateUtils.addMilliseconds(fechaHasta, -1));
                break;
            case 3:
                calendar = DateUtils.truncate(calendar, Calendar.DAY_OF_MONTH);
                calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
                setFechaDesde(calendar.getTime());
                break;
            case 4:
                setFechaDesde(DateUtils.truncate(new Date(), Calendar.MONTH));
                break;
            case 5:
                setFechaDesde(DateUtils.truncate(new Date(), Calendar.YEAR));
                break;
            }
        }
    } catch (Exception ex) {
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", ex.getMessage()));
    }
}

From source file:io.vit.vitio.Managers.DataHandler.java

public boolean isWeekend() {
    Calendar calendar = Calendar.getInstance();
    if (calendar.get(Calendar.DAY_OF_WEEK) == 1)
        return true;
    else/*from ww  w .  j  a  v a2 s  . c  om*/
        return false;
}

From source file:dao.Graficos.java

public static Date dia_inicial_final_semana(boolean isPrimeiro) {
    //Seta a data atual.
    Date dataAtual = new Date();
    GregorianCalendar calendar = new GregorianCalendar();
    //Define que a semana comea no domingo.
    calendar.setFirstDayOfWeek(Calendar.SUNDAY);
    //Define a data atual.
    calendar.setTime(dataAtual);/* w  w w  .j av  a 2  s .  c  o m*/
    if (isPrimeiro) {
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    } else {
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
    }
    return calendar.getTime();
}

From source file:net.sourceforge.fenixedu.presentationTier.TagLib.sop.examsMapNew.renderers.ExamsMapContentRenderer.java

private boolean onValidWeekDay(InfoExam infoExam) {
    int curricularYear = infoExam.getInfoExecutionCourse().getCurricularYear().intValue();
    int weekDay = infoExam.getDay().get(Calendar.DAY_OF_WEEK);

    return ((curricularYear == 1 || curricularYear == 3 || curricularYear == 5)
            && (weekDay == Calendar.MONDAY || weekDay == Calendar.WEDNESDAY || weekDay == Calendar.FRIDAY))
            || ((curricularYear == 2 || curricularYear == 4) && (weekDay == Calendar.TUESDAY
                    || weekDay == Calendar.THURSDAY || weekDay == Calendar.SATURDAY));
}