Example usage for java.util Calendar getFirstDayOfWeek

List of usage examples for java.util Calendar getFirstDayOfWeek

Introduction

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

Prototype

public int getFirstDayOfWeek() 

Source Link

Document

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

Usage

From source file:TripServlet.java

public Date getLastMonth() {
    Calendar c = Calendar.getInstance();
    c = (Calendar) c.clone();/*from   w  w w.  ja  v  a  2 s. c  o  m*/
    c.add(Calendar.MONTH, -1);// last month
    c.set(Calendar.DAY_OF_MONTH, c.getFirstDayOfWeek());
    Date date = c.getTime();
    return date;
}

From source file:TripServlet.java

public Date getLastWeek() {
    Calendar c = Calendar.getInstance();
    c = (Calendar) c.clone();/*ww  w.  j  ava2 s  .  co m*/
    c.add(Calendar.WEEK_OF_YEAR, -1);// last week
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
    Date date = c.getTime();
    return date;
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java

public static long[] parseTimePeriod(String timeperiod) {

    if (null == timeperiod)
        timeperiod = "last60minutes";

    Date fromDate = null;//from   w  w w.j ava 2 s  .c  o m
    Date toDate = null;
    long dataPoints = 60;

    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    // Reset the day fields so we're at the beginning of the day.
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    // Compute "this week" by resetting the day of the week to the first day of the week
    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
    Date thisWeekStart = cal.getTime();
    Date thisWeekEnd = now;
    // Compute last week - start with the end boundary which is 1 millisecond before the start of this week
    cal.add(Calendar.MILLISECOND, -1);
    Date lastWeekEnd = cal.getTime();
    // Add that millisecond back, subtract 7 days for the start boundary of "last week"
    cal.add(Calendar.MILLISECOND, 1);
    cal.add(Calendar.DAY_OF_YEAR, -7);
    Date lastWeekStart = cal.getTime();
    // Reset the time
    cal.setTime(now);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    // Reset to the 1st day of the month, make the the start boundary for "this month"
    cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DAY_OF_MONTH));
    Date thisMonthStart = cal.getTime();
    Date thisMonthEnd = now;
    // Compute last month
    cal.add(Calendar.MILLISECOND, -1);
    Date lastMonthEnd = cal.getTime();
    cal.add(Calendar.MILLISECOND, 1);
    cal.add(Calendar.MONTH, -1);
    Date lastMonthStart = cal.getTime();
    // Compute last 3 months
    cal.setTime(now);
    cal.add(Calendar.MONTH, -2);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date last3MonthsStart = cal.getTime();
    Date last3MonthsEnd = now;
    // Compute last 7 days:
    cal.setTime(now);
    cal.add(Calendar.DAY_OF_YEAR, -6);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date last7DaysStart = cal.getTime();
    Date last7DaysEnd = now;
    // Compute last 60 minutes;
    cal.setTime(now);
    cal.add(Calendar.MINUTE, -60);
    Date last60MinutesStart = cal.getTime();
    Date last60MinutesEnd = now;
    // Compute last 24 hours;
    cal.setTime(now);
    cal.add(Calendar.HOUR, -23);
    Date last24HoursStart = cal.getTime();
    Date last24HoursEnd = now;
    // Done, reset the cal internal date to now
    cal.setTime(now);

    if ("thisweek".equals(timeperiod)) {
        fromDate = thisWeekStart;
        toDate = thisWeekEnd;
        dataPoints = 7;
    } else if ("last7days".equals(timeperiod)) {
        fromDate = last7DaysStart;
        toDate = last7DaysEnd;
        dataPoints = 7;
    } else if ("lastweek".equals(timeperiod)) {
        fromDate = lastWeekStart;
        toDate = lastWeekEnd;
        dataPoints = 7;
    } else if ("thismonth".equals(timeperiod)) {
        fromDate = thisMonthStart;
        toDate = thisMonthEnd;
        dataPoints = 30;
    } else if ("lastmonth".equals(timeperiod)) {
        fromDate = lastMonthStart;
        toDate = lastMonthEnd;
        dataPoints = 30;
    } else if ("last3months".equals(timeperiod)) {
        fromDate = last3MonthsStart;
        toDate = last3MonthsEnd;
        dataPoints = (long) Math.ceil((toDate.getTime() - fromDate.getTime()) / WEEK);
    } else if ("last60minutes".equals(timeperiod)) {
        fromDate = last60MinutesStart;
        toDate = last60MinutesEnd;
        dataPoints = 60;
    } else if ("last24hours".equals(timeperiod)) {
        fromDate = last24HoursStart;
        toDate = last24HoursEnd;
        dataPoints = 48;
    } else {
        String[] dates = timeperiod.split("to");
        if (dates.length > 0) {
            DateFormat formDateFormatter = new SimpleDateFormat("MM/dd/yy");
            String fromDateParam = dates[0];
            String toDateParam = dates[1];
            if (fromDateParam != null) {
                try {
                    fromDate = formDateFormatter.parse(fromDateParam);
                } catch (Exception e) {
                    // ignore formatting exception
                }
            }
            if (toDateParam != null) {
                try {
                    toDate = formDateFormatter.parse(toDateParam);
                    // Make this date be the end of the day (so it's the day *inclusive*, not *exclusive*)
                    Calendar adjusted = Calendar.getInstance();
                    adjusted.setTime(toDate);
                    adjusted.set(Calendar.HOUR_OF_DAY, 23);
                    adjusted.set(Calendar.MINUTE, 59);
                    adjusted.set(Calendar.SECOND, 59);
                    adjusted.set(Calendar.MILLISECOND, 999);
                    toDate = adjusted.getTime();
                } catch (Exception e) {
                    // ignore formatting exception
                }
            }
            dataPoints = discoverDataPoints(fromDate, toDate);
        }
    }

    // default to last 60 minutes
    if (null == fromDate && null == toDate) {
        return new long[] { last60MinutesStart.getTime(), last60MinutesEnd.getTime(), dataPoints };
    } else if (null == fromDate) {
        return new long[] { 0, toDate.getTime(), dataPoints };
    } else if (null == toDate) {
        return new long[] { fromDate.getTime(), now.getTime(), dataPoints };
    } else {
        return new long[] { fromDate.getTime(), toDate.getTime(), dataPoints };
    }
}

From source file:org.olat.commons.calendar.ui.components.FullCalendarComponentRenderer.java

@Override
public void render(Renderer renderer, StringOutput sb, Component source, URLBuilder ubu, Translator translator,
        RenderResult renderResult, String[] args) {

    FullCalendarComponent fcC = (FullCalendarComponent) source;
    FullCalendarElement fcE = fcC.getCalendarElement();
    Form rootForm = fcE.getRootForm();//from   w  w w  .j  ava  2 s.c  om
    String id = "o_c" + fcC.getDispatchID();
    String formId = fcE.getFormDispatchId();
    String printId = "fc_p" + fcC.getDispatchID();

    Calendar cal = Calendar.getInstance(fcC.getTranslator().getLocale());
    int firstDay = cal.getFirstDayOfWeek() - 1;
    cal = Calendar.getInstance();
    cal.setTime(fcC.getCurrentDate());

    Calendar calRef = Calendar.getInstance(fcC.getTranslator().getLocale());
    calRef.set(Calendar.DATE, 25);
    calRef.set(Calendar.MONTH, 11);
    calRef.set(Calendar.YEAR, 2013);

    String formatted = DateFormat.getDateInstance(DateFormat.SHORT, fcC.getTranslator().getLocale())
            .format(calRef.getTime());
    boolean firstMonth = (formatted.indexOf("12") < formatted.indexOf("25"));

    String amFormatted = DateFormat.getTimeInstance(DateFormat.SHORT, fcC.getTranslator().getLocale())
            .format(calRef.getTime());
    boolean ampm = amFormatted.contains("AM") || amFormatted.contains("PM");

    sb.append("<script type='text/javascript'>\n").append("/* <![CDATA[ */ \n").append("jQuery(function() {\n")
            .append("   jQuery('#").append(id).append("').fullCalendar( {\n").append("   header: {\n")
            .append("     left: 'prev,print,next today',\n").append("     center: 'title',\n")
            .append("     right: 'month,agendaWeek,agendaDay'\n").append("   },\n").append("   buttonText: {\n")
            .append("     today: '").append(escapeJavaScript(translator.translate("cal.thisweek")))
            .append("',\n").append("     month: '").append(escapeJavaScript(translator.translate("cal.month")))
            .append("',\n").append("     day: '").append(escapeJavaScript(translator.translate("cal.day")))
            .append("',\n").append("     week: '").append(escapeJavaScript(translator.translate("cal.week")))
            .append("',\n").append("     print: '").append(escapeJavaScript(translator.translate("print")))
            .append("'\n").append("   },\n").append("   monthNames: ").append(getMonthLong(translator))
            .append(",\n").append("   monthNamesShort: ").append(getMonthShort(translator)).append(",\n")
            .append("   dayNames: ").append(getDayLong(translator)).append(",\n").append("   dayNamesShort: ")
            .append(getDayShort(translator)).append(",\n").append("   allDayText:'")
            .append(translator.translate("cal.form.allday")).append("',\n").append("   axisFormat:'")
            .append(ampm ? "h(:mm)tt" : "H.mm").append("',\n").append("   timeFormat:'")
            .append(ampm ? "h(:mm)tt" : "H.mm").append("',\n").append("   titleFormat: {\n")
            .append("     month: 'MMMM yyyy',\n").append("     week: ")
            .append(firstMonth ? "\"MMM d[ yyyy]{ '&#8212;'[ MMM] d yyyy}\""
                    : "\"d. [ MMM] [ yyyy]{ '&#8212;' d. MMM yyyy}\"")
            .append(",\n").append("     day: ")
            .append(firstMonth ? "'dddd, MMM d, yyyy'" : "'dddd, d. MMM yyyy'").append("\n").append("   },\n")
            .append("   columnFormat: {\n").append("     month: 'ddd',\n").append("     week: ")
            .append(firstMonth ? "'ddd M/d'" : "'ddd d.M.'").append(",\n").append("     day: ")
            .append(firstMonth ? "'dddd M/d'" : "'dddd d.M.'").append("\n").append("   },\n").append("   year:")
            .append(cal.get(Calendar.YEAR)).append(",\n").append("   month:").append(cal.get(Calendar.MONTH))
            .append(",\n").append("   date:").append(cal.get(Calendar.DAY_OF_MONTH)).append(",\n")
            .append("   firstDay:").append(firstDay).append(",\n").append("   defaultView:'")
            .append(fcC.getViewName()).append("',\n").append("   weekNumbers: true,\n")
            .append("   editable: true,\n").append("   selectable: true,\n").append("   selectHelper: true,\n")
            .append("     eventSources:[");
    int count = 0;
    for (KalendarRenderWrapper calWrapper : fcC.getKalendarRenderWrappers()) {
        if (calWrapper.getKalendarConfig().isVis()) {
            String calId = calWrapper.getKalendar().getCalendarID();
            String color = calWrapper.getKalendarConfig().getCss();
            if (StringHelper.containsNonWhitespace(color) && color.startsWith("o_cal_")) {
                color = color.substring(6, color.length());
            }
            if (count++ != 0)
                sb.append(",");
            sb.append("{\n").append("   url:'").append(fcC.getMapperUrl()).append("/").append(calId)
                    .append(".json',\n").append("   color:'").append(color).append("'\n").append("}");
        }
    }
    sb.append("   ],\n").append("   eventAfterRender: function(event, element, view) {\n")
            .append("     element.each(function(index, el) {\n")
            .append("       jQuery(el).attr('id', 'o_cev_' + view.name + '_' + event.id);\n")
            .append("     });\n").append("   },\n").append("   viewDisplay: function(view) {\n")
            .append(FormJSHelper.generateXHRFnCallVariables(rootForm, formId, 1))
            .append("     o_ffXHREvent(formNam, dispIdField, dispId, eventIdField, eventInt,'evChangeView',view.name,'start',view.start.getTime());\n")
            .append("   },\n")
            .append("     eventDrop: function(calEvent, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {\n")
            .append(FormJSHelper.generateXHRFnCallVariables(rootForm, formId, 1))
            .append("     o_ffXHREvent(formNam, dispIdField, dispId, eventIdField, eventInt,'evMove',calEvent.id,'dayDelta',dayDelta,'minuteDelta',minuteDelta,'allDay',allDay);\n")
            .append("     },\n").append("   select: function(startDate, endDate, allDay, jsEvent, view) {\n")
            .append(FormJSHelper.generateXHRFnCallVariables(rootForm, formId, 1))
            .append("     o_ffXHREvent(formNam, dispIdField, dispId, eventIdField, eventInt,'evAdd','new','start',startDate.getTime(),'end',endDate.getTime(),'allDay',allDay);\n")
            .append("   },\n").append("   eventClick: function(calEvent, jsEvent, view) {\n")
            .append(FormJSHelper.generateXHRFnCallVariables(rootForm, formId, 1))
            .append("     o_ffXHREvent(formNam, dispIdField, dispId, eventIdField, eventInt,'evSelect',calEvent.id,'evDomId','o_cev_' + view.name + '_' + calEvent.id);\n")
            .append("   }\n").append(" });\n")
            .append(" jQuery('.fc-header-left').append('<span class=\"fc-header-space\"></span><span id=\"")
            .append(printId)
            .append("\" class=\"fc-button fc-button-print fc-state-default fc-corner-left fc-corner-right\"><span>")
            .append(translator.translate("print")).append("</span></span>');\n")
            .append(" jQuery('.fc-button-print').click(function () {\n")
            .append(FormJSHelper.generateXHRFnCallVariables(rootForm, formId, 1))
            .append("   o_ffXHREvent(formNam, dispIdField, dispId, eventIdField, eventInt,'print','print');\n")
            .append(" });\n").append("});\n").append("/* ]]> */\n").append("</script>");
}

From source file:org.onebusaway.webapp.actions.where.ScheduleAction.java

public List<String> getShortWeekDays() {

    List<String> result = new ArrayList<String>();
    DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(getLocale());

    String shortWeekdays[] = dateFormatSymbols.getShortWeekdays();
    Calendar calendar = Calendar.getInstance(getLocale());
    int firstDayOfWeek = calendar.getFirstDayOfWeek();

    for (int dayOfWeek = firstDayOfWeek; dayOfWeek < shortWeekdays.length; dayOfWeek++) {
        result.add(shortWeekdays[dayOfWeek]);
    }//from  w ww  . jav a  2 s .co  m

    for (int dayOfWeek = Calendar.SUNDAY; dayOfWeek < firstDayOfWeek; dayOfWeek++) {
        result.add(shortWeekdays[dayOfWeek]);
    }

    return result;
}

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

/**
 * {@inheritDoc}/*from   w  ww. jav a2 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.apache.lens.cube.metadata.UpdatePeriod.java

public Date truncate(Date date) {
    switch (this) {
    case WEEKLY://from  w w w  .  jav  a  2s  . com
        Date truncDate = DateUtils.truncate(date, Calendar.DAY_OF_MONTH);
        Calendar cal = Calendar.getInstance();
        cal.setTime(truncDate);
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        return cal.getTime();
    case QUARTERLY:
        Date dt = DateUtils.truncate(date, this.calendarField());
        dt.setMonth(dt.getMonth() - (dt.getMonth() % 3));
        return dt;
    default:
        return DateUtils.truncate(date, this.calendarField());
    }
}

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

/**
 * ??/*from w  w  w .j av  a2 s  . 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:org.apache.roller.weblogger.ui.core.tags.calendar.CalendarTag.java

/**
 * Helper method to build the names of the weekdays. This
 * used to take place in the <code>CalendarTag</code> constructor,
 * but there, <code>mLocale</code> doesn't have the correct value yet.
 *//*from   w  w  w .  j a va  2  s .  c  o  m*/
private void buildDayNames() {
    // build array of names of days of week
    mDayNames = new String[7];
    Calendar dayNameCal = Calendar.getInstance(mLocale);
    SimpleDateFormat dayFormatter = new SimpleDateFormat("EEE", mLocale);
    dayNameCal.set(Calendar.DAY_OF_WEEK, dayNameCal.getFirstDayOfWeek());
    for (int dnum = 0; dnum < 7; dnum++) {
        mDayNames[dnum] = dayFormatter.format(dayNameCal.getTime());
        dayNameCal.add(Calendar.DATE, 1);
    }
}

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

/**
 * {@inheritDoc}/* ww  w.j  a va  2s. 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);
}