Example usage for java.util Calendar setFirstDayOfWeek

List of usage examples for java.util Calendar setFirstDayOfWeek

Introduction

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

Prototype

public void setFirstDayOfWeek(int value) 

Source Link

Document

Sets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.

Usage

From source file:org.power.commons.lang.util.time.DateUtils.java

/**
 * ??/* w w  w  .  j  a  va 2s  . c  o  m*/
 *
 * @param date
 * @return
 * @author yang_yun
 */
public static Date getFirstDayOfLastWeek(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(date.getTime() - 604800000L);
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    Date lastWeekDate = c.getTime();

    c = new GregorianCalendar();
    c.setFirstDayOfWeek(Calendar.MONDAY);
    c.setTime(new Date(lastWeekDate.getTime()));
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
    return c.getTime();
}

From source file:com.siblinks.ws.service.impl.VideoSubscriptionsServiceImpl.java

/**
 * {@inheritDoc}/*from  www.  j  ava2  s  . c  om*/
 */
@Override
@RequestMapping(value = "/getListVideoOfWeek", method = RequestMethod.POST)
public ResponseEntity<Response> getListVideoOfWeek(@RequestParam("subjectId") final String subjectId) {
    SimpleResponse response = null;
    try {
        String method = "getListVideoOfWeek()";

        logger.debug(method + " start");

        String entityName = null;
        List<Object> readObject = null;
        String currentDate = "";
        String firstDayOfCurrentWeek = "";

        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
            Date firstDayOfTheWeek = cal.getTime();

            currentDate = DateUtil.date2YYYYMMDD000000(new Date());
            firstDayOfCurrentWeek = DateUtil.date2YYYYMMDD000000(firstDayOfTheWeek);

            System.out.println(firstDayOfCurrentWeek);

            entityName = SibConstants.SqlMapper.SQL_SIB_GET_LIST_VIDEO_OF_WEEK;

            Object[] queryParams = { subjectId, firstDayOfCurrentWeek, currentDate };

            readObject = dao.readObjects(entityName, queryParams);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        response = new SimpleResponse("true", readObject);
    } catch (Exception e) {
        logger.error(e.getMessage());
        response = new SimpleResponse(SibConstants.FAILURE, "videoAdmission", "getVideoTuttorialAdmission",
                e.getMessage());
    }
    return new ResponseEntity<Response>(response, HttpStatus.OK);
}

From source file:org.b3log.symphony.processor.JournalProcessor.java

/**
 * Generates journal chapter this week.//from  w w  w  .j  a v a2 s. c o  m
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @throws IOException io exception
 * @throws ServletException servlet exception
 */
@RequestProcessing(value = "/journal/gen/chapter", method = HTTPRequestMethod.GET)
@Before(adviceClass = StopwatchStartAdvice.class)
@After(adviceClass = StopwatchEndAdvice.class)
public void genChapter(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    final String key = Symphonys.get("keyOfSymphony");
    if (!key.equals(request.getParameter("key"))) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);

        return;
    }

    context.renderJSON();

    if (journalQueryService.hasChapterWeek()) {
        return;
    }

    try {
        final JSONObject admin = userQueryService.getSA();

        final JSONObject chapter = new JSONObject();

        final Calendar cal = Calendar.getInstance();
        final SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        final String from = df.format(cal.getTime());
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

        final String title = from + " - " + df.format(cal.getTime());
        chapter.put(Article.ARTICLE_TITLE, title);
        chapter.put(Article.ARTICLE_TAGS, ",");
        chapter.put(Article.ARTICLE_CONTENT, "");
        chapter.put(Article.ARTICLE_EDITOR_TYPE, 0);
        chapter.put(Article.ARTICLE_AUTHOR_EMAIL, admin.optString(User.USER_EMAIL));
        chapter.put(Article.ARTICLE_AUTHOR_ID, admin.optString(Keys.OBJECT_ID));
        chapter.put(Article.ARTICLE_TYPE, Article.ARTICLE_TYPE_C_JOURNAL_CHAPTER);

        articleMgmtService.addArticle(chapter);

        context.renderTrueResult();
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, "Generates section failed", e);
    }
}

From source file:com.siblinks.ws.service.impl.VideoSubscriptionsServiceImpl.java

/**
 * {@inheritDoc}/*  www .j a va2  s.  c  o m*/
 */
@Override
@RequestMapping(value = "/getListVideoSubscription", method = RequestMethod.GET)
public ResponseEntity<Response> getListVideoSubscription(@RequestParam("userId") final String userId,
        @RequestParam("subjectId") final String subjectId) {
    SimpleResponse response = null;
    try {
        String method = "getListVideoSubscription()";
        logger.debug(method + " start");

        String entityName = null;
        List<Object> readObject = null;
        String currentDate = "";
        String firstDayOfCurrentWeek = "";
        Object[] queryParams = null;
        Map<String, List<Object>> mapListVideo = new HashMap<String, List<Object>>();

        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
            Date firstDayOfTheWeek = cal.getTime();

            currentDate = DateUtil.date2YYYYMMDD000000(new Date());
            firstDayOfCurrentWeek = DateUtil.date2YYYYMMDD000000(firstDayOfTheWeek);

            if ("-2".equals(subjectId)) {
                entityName = SibConstants.SqlMapper.SQL_SIB_GET_ALL_VIDEO_SUBSCRIPTION;
                queryParams = new Object[] { userId, currentDate, userId, firstDayOfCurrentWeek, currentDate,
                        userId, firstDayOfCurrentWeek };
                readObject = dao.readObjects(entityName, queryParams);
            } else {
                // Get child category by subjectId
                List<Map<String, Object>> readObjectNoCondition = dao
                        .readObjectNoCondition(SibConstants.SqlMapper.SQL_GET_ALL_CATEGORY_TOPIC);

                MapSqlParameterSource params = new MapSqlParameterSource();

                String allChildCategory = CommonUtil.getAllChildCategory(subjectId, readObjectNoCondition);
                if (!StringUtil.isNull(allChildCategory)) {
                    List<Integer> listChildCategory = new ArrayList<Integer>();
                    String[] arrChildCategory = allChildCategory.split(",");
                    for (String string : arrChildCategory) {
                        listChildCategory.add(Integer.parseInt(string));
                    }
                    params.addValue("subjectID", listChildCategory);

                }
                params.addValue("userID", userId);
                params.addValue("currentDate", currentDate);
                params.addValue("firstDayOfCurrentWeek", firstDayOfCurrentWeek);

                entityName = SibConstants.SqlMapper.SQL_SIB_GET_ALL_VIDEO_SUBSCRIPTION_BY_CATEGORY;

                readObject = dao.readObjectNamedParameter(entityName, params);
            }

            if (readObject == null) {
                readObject = new ArrayList<Object>();
            }

            JSONArray jsonAraay = new JSONArray(readObject);

            for (int i = 0; i < jsonAraay.length(); i++) {
                JSONObject jsonObj = jsonAraay.getJSONObject(i);
                ObjectMapper mapper = new ObjectMapper();
                Object obj = mapper.readValue(jsonObj.toString(), Object.class);
                addMapVideo(mapListVideo, jsonObj.get("flag").toString(), obj);
            }

        } catch (ParseException | IOException e) {
            logger.error(method + " - error : " + e.getMessage());
        }

        response = new SimpleResponse("true", mapListVideo);
    } catch (Exception e) {
        e.printStackTrace();
        response = new SimpleResponse(SibConstants.FAILURE, "video", "getListVideoSubscription",
                e.getMessage());
    }
    return new ResponseEntity<Response>(response, HttpStatus.OK);
}

From source file:com.glaf.core.web.springmvc.WorkCalendarController.java

/**
 * /*from ww  w.  j  av a2  s .  co  m*/
 * 
 * @param request
 * @param modelMap
 * @return
 */
@RequestMapping("/showCalendar")
public ModelAndView showCalendar(HttpServletRequest request, ModelMap modelMap) {
    Calendar cal = Calendar.getInstance();
    int month = RequestUtils.getIntParameter(request, "month", cal.get(Calendar.MONTH));
    int year = RequestUtils.getIntParameter(request, "year", cal.get(Calendar.YEAR));

    cal.set(Calendar.MONTH, month); // 
    cal.set(Calendar.YEAR, year); // 
    cal.setFirstDayOfWeek(Calendar.SUNDAY);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    logger.info("month:" + month);
    int firstIndex = cal.get(Calendar.DAY_OF_WEEK) - 1; // 
    logger.info("firstIndex:" + firstIndex);
    int maxIndex = cal.getActualMaximum(Calendar.DAY_OF_MONTH);// 
    logger.info("maxIndex:" + maxIndex);
    int weeks = Calendar.WEEK_OF_MONTH;// 
    cal.set(Calendar.DATE, 1);// 1?
    if (cal.get(Calendar.DAY_OF_WEEK) == 7)
        weeks += 1;
    logger.info("day of week:" + cal.get(Calendar.DAY_OF_WEEK));
    logger.info("weeks:" + weeks);

    String days[] = new String[42];
    for (int i = 0; i < 42; i++) {
        days[i] = "";
    }
    for (int i = 0; i < maxIndex; i++) {
        days[firstIndex + i] = String.valueOf(i + 1);
    }

    List<Integer> list = workCalendarService.getWorkDateList(year, month + 1);
    if (list == null) {
        list = new java.util.ArrayList<Integer>();
    }

    request.setAttribute("list", list);
    request.setAttribute("year", String.valueOf(year));
    request.setAttribute("month", String.valueOf(month));
    request.setAttribute("weeks", String.valueOf(weeks));
    request.setAttribute("days", days);

    String x_view = ViewProperties.getString("calendar.showCalendar");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view, modelMap);
    }

    return new ModelAndView("/modules/sys/calendar/calendar", modelMap);
}

From source file:org.springmodules.validation.util.date.DefaultDateParser.java

private Date simpleParse(String str, Date t) throws DateParseException {
    for (Iterator iter = this.registrations.keySet().iterator(); iter.hasNext();) {
        RegexpPredicate predicate = (RegexpPredicate) iter.next();
        if (predicate.evaluate(str)) {
            Object dateParser = this.registrations.get(predicate);
            if (dateParser instanceof DateParser) {
                return ((DateParser) dateParser).parse(str);
            } else if (dateParser instanceof DateModifier) {
                Calendar calendar = new GregorianCalendar();
                calendar.setFirstDayOfWeek(Calendar.MONDAY);
                if (t == null) {
                    calendar.setTime(new Date());
                } else {
                    calendar.setTime(t);
                }/*from   ww  w.j a v  a2 s  .co  m*/
                ((DateModifier) dateParser).modify(calendar, predicate.getGroup1(str));
                return calendar.getTime();
            }
        }
    }

    return null;
}

From source file:com.rogchen.common.xml.UtilDateTime.java

public static int weekNumber(Timestamp input, int startOfWeek) {
    Calendar calendar = Calendar.getInstance();
    calendar.setFirstDayOfWeek(startOfWeek);

    if (startOfWeek == Calendar.MONDAY) {
        calendar.setMinimalDaysInFirstWeek(4);
    } else if (startOfWeek == Calendar.SUNDAY) {
        calendar.setMinimalDaysInFirstWeek(3);
    }//from w  ww .  ja v  a2  s.c om

    calendar.setTime(new Date(input.getTime()));
    return calendar.get(Calendar.WEEK_OF_YEAR);
}

From source file:org.apps8os.motivator.ui.MoodHistoryActivity.java

/**
 * Used to set the selected day and week of the sprint in the activity.
 * @param dayInMillis/*ww w  .ja v a  2  s .co m*/
 */
public void setSelectedDay(long dayInMillis) {
    // Calculate the selected day position in the viewpager
    mSelectedDay = (int) TimeUnit.DAYS.convert(dayInMillis - mSprintStartDateInMillis, TimeUnit.MILLISECONDS);
    Calendar selectedDayAsCalendar = Calendar.getInstance();
    selectedDayAsCalendar.setFirstDayOfWeek(Calendar.MONDAY);
    selectedDayAsCalendar.setTimeInMillis(dayInMillis);
    // Calculate the selected day position as week in the viewpager
    mSelectedWeek = selectedDayAsCalendar.get(Calendar.WEEK_OF_YEAR) - mStartDate.get(Calendar.WEEK_OF_YEAR);
    // Take into account change of year.
    if (mSelectedWeek < 0) {
        mSelectedWeek = 52 - mStartDate.get(Calendar.WEEK_OF_YEAR)
                + selectedDayAsCalendar.get(Calendar.WEEK_OF_YEAR);
    } else {
    }
    // Set the day or week depending on orientation.
    if (mRes.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        mViewPager.setCurrentItem(mSelectedDay);
    } else if (mRes.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        mViewPager.setCurrentItem(mSelectedWeek);
    }
}

From source file:org.apps8os.motivator.ui.MoodHistoryActivity.java

/** Called when the activity is first created. */
@Override/* www.ja va 2  s  . c o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mood_history);
    mDayDataHandler = new DayDataHandler(this);

    mCurrentSprint = getIntent().getExtras().getParcelable(Sprint.CURRENT_SPRINT);
    mRes = getResources();
    mSprintStartDateInMillis = mCurrentSprint.getStartTime();
    mSprintEndDateInMillis = mCurrentSprint.getEndTime();

    mDaysInSprint = mCurrentSprint.getDaysInSprint();
    ActionBar actionBar = getActionBar();

    Calendar mToday = Calendar.getInstance();
    UtilityMethods.setToDayStart(mToday);
    mToday.setFirstDayOfWeek(Calendar.MONDAY);

    mNumberOfTodayInSprint = mCurrentSprint.getCurrentDayOfTheSprint();

    // Check if the sprint is already over.
    if (mNumberOfTodayInSprint > mDaysInSprint) {
        mNumberOfTodayInSprint = mDaysInSprint;
    }
    actionBar.setSubtitle(mCurrentSprint.getSprintTitle());
    actionBar.setTitle(mNumberOfTodayInSprint + " " + getString(R.string.days));
    actionBar.setBackgroundDrawable(mRes.getDrawable(R.drawable.action_bar_orange));

    mStartDate = Calendar.getInstance();
    mStartDate.setFirstDayOfWeek(Calendar.MONDAY);
    mStartDate.setTimeInMillis(mSprintStartDateInMillis);

    // Calculate the number of weeks in the sprint
    mNumberOfWeeksInSprint = mToday.get(Calendar.WEEK_OF_YEAR) - mStartDate.get(Calendar.WEEK_OF_YEAR) + 1;
    if (mNumberOfWeeksInSprint < 0) {
        mNumberOfWeeksInSprint = 52 + 1 - mStartDate.get(Calendar.WEEK_OF_YEAR)
                + mToday.get(Calendar.WEEK_OF_YEAR);
    } else {

    }

    // Sets the default selections as today or this week.
    mSelectedDay = mNumberOfTodayInSprint - 1;
    mSelectedWeek = mNumberOfWeeksInSprint - 1;
    mViewPager = (ViewPager) findViewById(R.id.activity_mood_history_viewpager);

    titleIndicator = (TitlePageIndicator) findViewById(R.id.indicator);

    // Page change listener to keep the selected week and day in a member.
    titleIndicator.setOnPageChangeListener(new OnPageChangeListener() {
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            if (mRes.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                mSelectedDay = arg0;
            } else if (mRes.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                mSelectedWeek = arg0;
                MoodHistoryWeekFragment fragment = mPagerAdapterWeek.getWeekFragment(arg0);
                if (fragment != null) {
                    fragment.updateSelectedAttribute(mSelectedAttribute, false);
                }
            }
        }
    });

    setPageTitles();

    // Load correct layout and functionality based on orientation
    if (mRes.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        loadPortraitView();
    } else if (mRes.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        loadLandscapeView();
    }

}

From source file:org.goobi.production.flow.statistics.StatisticsManager.java

/**
 * Depending on selected Dates oder time range, set the dates for the
 * statistical question here.//from  w w  w . j av  a  2 s.  com
 *
 * @param question
 *            the {@link IStatisticalQuestion} where the dates should be set, if
 *            it is an implementation of
 *            {@link IStatisticalQuestionLimitedTimeframe}
 */
@SuppressWarnings("incomplete-switch")
private void setTimeFrameToStatisticalQuestion(IStatisticalQuestion question) {
    /* only add a date, if correct interface is implemented here */
    if (question instanceof IStatisticalQuestionLimitedTimeframe) {
        /* if a timeunit is selected calculate the dates */
        Calendar cl = Calendar.getInstance();

        if (sourceNumberOfTimeUnits > 0) {

            cl.setFirstDayOfWeek(Calendar.MONDAY);
            cl.setTime(new Date());

            switch (sourceTimeUnit) {
            case days:
                calculatedEndDate = calulateStartDateForTimeFrame(cl);
                calculatedStartDate = calculateEndDateForTimeFrame(cl, Calendar.DATE, -1);
                break;

            case weeks:
                cl.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                calculatedEndDate = calulateStartDateForTimeFrame(cl);
                calculatedStartDate = calculateEndDateForTimeFrame(cl, Calendar.DATE, -7);
                break;

            case months:
                cl.set(Calendar.DAY_OF_MONTH, 1);
                calculatedEndDate = calulateStartDateForTimeFrame(cl);
                calculatedStartDate = calculateEndDateForTimeFrame(cl, Calendar.MONTH, -1);
                break;

            case quarters:
                cl.set(Calendar.DAY_OF_MONTH, 1);
                setCalendarToMidnight(cl);
                while ((cl.get(Calendar.MONTH)) % 3 > 0) {
                    cl.add(Calendar.MONTH, -1);
                }
                cl.add(Calendar.MILLISECOND, -1);
                calculatedEndDate = cl.getTime();
                calculatedStartDate = calculateEndDateForTimeFrame(cl, Calendar.MONTH, -3);
                break;

            case years:
                cl.set(Calendar.DAY_OF_YEAR, 1);
                calculatedEndDate = calulateStartDateForTimeFrame(cl);
                calculatedStartDate = calculateEndDateForTimeFrame(cl, Calendar.YEAR, -1);
                break;
            }

        } else {
            /* take start and end date */
            cl.setTime(sourceDateTo);
            cl.add(Calendar.DATE, 1);
            setCalendarToMidnight(cl);
            cl.add(Calendar.MILLISECOND, -1);
            calculatedStartDate = sourceDateFrom;
            calculatedEndDate = cl.getTime();
        }
        ((IStatisticalQuestionLimitedTimeframe) question).setTimeFrame(calculatedStartDate, calculatedEndDate);
    } else {
        calculatedStartDate = null;
        calculatedEndDate = null;
    }
}