List of usage examples for java.util Calendar SUNDAY
int SUNDAY
To view the source code for java.util Calendar SUNDAY.
Click Source Link
From source file:org.apache.lens.cube.metadata.DateUtil.java
public static CoveringInfo getWeeklyCoveringInfo(Date from, Date to) { int dayDiff = 0; Date tmpFrom = from;/*from w ww . j a va 2 s .c o m*/ while (tmpFrom.before(to)) { tmpFrom = DateUtils.addDays(tmpFrom, 1); dayDiff++; } if (dayDiff < 7) { return new CoveringInfo(0, false); } Calendar cal = Calendar.getInstance(); cal.setTime(from); int fromDay = cal.get(Calendar.DAY_OF_WEEK); cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); Date fromWeekStartDate = cal.getTime(); boolean coverable = dayDiff % 7 == 0; if (fromWeekStartDate.before(from)) { // Count from the start of next week dayDiff -= (cal.getActualMaximum(Calendar.DAY_OF_WEEK) - (fromDay - Calendar.SUNDAY)); coverable = false; } return new CoveringInfo(dayDiff / 7, coverable); }
From source file:org.nuclos.common2.DateUtils.java
private static void calc(GregorianCalendar result, CalcFunction cf, CalcPair cp) { switch (cf) { case ADD:// ww w.j a v a2 s .co m result.add(cp.x, cp.y); break; case SUBTRACT: result.add(cp.x, cp.y * (-1)); break; case SET: switch (cp.x) { case Calendar.YEAR: result.set(Calendar.DAY_OF_YEAR, cp.y == Integer.MIN_VALUE ? result.getActualMinimum(Calendar.DAY_OF_YEAR) : result.getActualMaximum(Calendar.DAY_OF_YEAR)); break; case Calendar.MONTH: result.set(Calendar.DAY_OF_MONTH, cp.y == Integer.MIN_VALUE ? result.getActualMinimum(Calendar.DAY_OF_MONTH) : result.getActualMaximum(Calendar.DAY_OF_MONTH)); break; case Calendar.WEEK_OF_YEAR: result.set(Calendar.DAY_OF_WEEK, cp.y == Integer.MIN_VALUE ? Calendar.MONDAY : Calendar.SUNDAY); break; } break; } }
From source file:org.openmrs.web.servlet.QuickReportServlet.java
private void doVoidedObs(VelocityContext velocityContext, PrintWriter report, HttpServletRequest request) throws ServletException { ObsService os = Context.getObsService(); DateFormat dateFormat = Context.getDateFormat(); velocityContext.put("date", dateFormat); Calendar cal = Calendar.getInstance(); Date start;/*from w w w . j a va 2 s . c om*/ Date end; String startDate = request.getParameter("startDate"); String endDate = request.getParameter("endDate"); if (startDate != null && startDate.length() != 0) { try { cal.setTime(dateFormat.parse(startDate)); } catch (ParseException e) { throw new ServletException("Error parsing 'Start Date'", e); } } else { cal.setTime(new Date()); } // if they don't input an end date, assume they meant "this week" if (StringUtils.isEmpty(endDate)) { while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) { cal.add(Calendar.DAY_OF_MONTH, -1); } start = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, 7); end = cal.getTime(); } else { // they put in an end date, assume literal start and end start = cal.getTime(); try { cal.setTime(dateFormat.parse(endDate)); } catch (ParseException e) { throw new ServletException("Error parsing 'End Date'", e); } end = cal.getTime(); } List<Obs> allObs = null; allObs = os.getObservations(null, null, null, null, null, null, null, null, null, start, end, true); List<Obs> obs = new Vector<Obs>(); for (Obs o : allObs) { if (o.getVoided()) { obs.add(o); } } velocityContext.put("observations", obs); }
From source file:org.jasig.schedassist.model.AvailableBlockBuilderTest.java
/** * Create blocks that span noon.//from ww w .ja va 2 s .c o m * * @throws Exception */ @Test public void testCreateBlocksExample4() throws Exception { SimpleDateFormat dateFormat = CommonDateOperations.getDateFormat(); Date startDate = dateFormat.parse("20080601"); Date endDate = dateFormat.parse("20080630"); Set<AvailableBlock> blocks = AvailableBlockBuilder.createBlocks("11:45 AM", "12:15 PM", "MTWRF", startDate, endDate); assertEquals(21, blocks.size()); for (AvailableBlock block : blocks) { assertEquals(30, block.getDurationInMinutes()); Calendar cal = Calendar.getInstance(); cal.setTime(block.getStartTime()); assertEquals(11, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(45, cal.get(Calendar.MINUTE)); cal.setTime(block.getEndTime()); assertEquals(12, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(15, cal.get(Calendar.MINUTE)); assertNotSame(Calendar.SATURDAY, cal.get(Calendar.DAY_OF_WEEK)); assertNotSame(Calendar.SUNDAY, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(1, block.getVisitorLimit()); } blocks = AvailableBlockBuilder.createBlocks("11:45 AM", "12:15 PM", "MTWRF", startDate, endDate, 2); assertEquals(21, blocks.size()); for (AvailableBlock block : blocks) { assertEquals(30, block.getDurationInMinutes()); Calendar cal = Calendar.getInstance(); cal.setTime(block.getStartTime()); assertEquals(11, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(45, cal.get(Calendar.MINUTE)); cal.setTime(block.getEndTime()); assertEquals(12, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(15, cal.get(Calendar.MINUTE)); assertNotSame(Calendar.SATURDAY, cal.get(Calendar.DAY_OF_WEEK)); assertNotSame(Calendar.SUNDAY, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(2, block.getVisitorLimit()); } }
From source file:com.hihframework.core.utils.DateUtils.java
/** * ??2004-07-28 ?/* ww w.j a v a 2 s .com*/ * * @param date * @return ? */ public static String getDayWeek(java.sql.Date date) { String days[] = { "", "", "", "", "", "", "" }; Calendar cale = Calendar.getInstance(); cale.setTime(date); cale.setFirstDayOfWeek(Calendar.SUNDAY); return date.toString() + " " + days[cale.get(Calendar.DAY_OF_WEEK) - 1]; }
From source file:com.sonymobile.androidapp.gridcomputing.fragments.ReportChartFragment.java
/** * Groups the original values into a sparse array. * The outer sparse array is indexed by the group field. * The inner sparse array is indexed by the index field. * If groupField and indexField are the same, then the outer sparse array contains only 1 entry * index by 0 and the inner sparse array is indexed by indexField. * @param original the original value returned from the SQL query. * @param groupField the field used to group the outer sparse array. * @param indexField the field used to group the inner sparse array. * @return a bidimensional sparse array indexed by groupField and indexField. *//* w w w . j a v a 2 s .c o m*/ private SparseArray<SparseArray<Double>> groupValues(final SparseArray<Pair<Date, Double>> original, final int groupField, final int indexField) { final Calendar calendar = Calendar.getInstance(); final SparseArray<SparseArray<Double>> weeks = new SparseArray<>(); for (int i = 0; i < original.size(); i++) { try { final int key = original.keyAt(i); calendar.setTime(original.get(key).first); final double value = original.get(key).second; final int indexValue = calendar.get(indexField); final int groupValue = groupField == indexField ? 0 : calendar.get(groupField); SparseArray<Double> currentWeek = weeks.get(groupValue); if (currentWeek == null) { currentWeek = new SparseArray<>(); weeks.put(groupValue, currentWeek); } currentWeek.put(indexValue, value); } catch (Exception e) { Log.e(e.getMessage()); } } // normalize the data // if the index field is DAY_OF_WEEK, then we'll add the remaining days to fill // the week from sunday until saturday if (indexField == Calendar.DAY_OF_WEEK) { for (int i = 0; i < weeks.size(); i++) { final int key = weeks.keyAt(i); SparseArray<Double> currentWeek = weeks.get(key); for (int j = Calendar.SUNDAY; j <= Calendar.SATURDAY; j++) { if (currentWeek.get(j) == null) { currentWeek.put(j, 0.0); } } } } return weeks; }
From source file:com.autentia.intra.bean.activity.ObjectiveBean.java
/** * Move a date to one of its surrounding fridays. * * @param d the reference date// w w w . ja v a 2 s. c om * @param inFuture whether to move to future/previous friday * @return the requested friday */ private Date moveToFriday(Date d, boolean inFuture) { Calendar cal = Calendar.getInstance(); cal.setTime(d); switch (cal.get(Calendar.DAY_OF_WEEK)) { case Calendar.MONDAY: cal.add(Calendar.DAY_OF_WEEK, inFuture ? 4 : -3); break; case Calendar.TUESDAY: cal.add(Calendar.DAY_OF_WEEK, inFuture ? 3 : -4); break; case Calendar.WEDNESDAY: cal.add(Calendar.DAY_OF_WEEK, inFuture ? 2 : -5); break; case Calendar.THURSDAY: cal.add(Calendar.DAY_OF_WEEK, inFuture ? 1 : -6); break; case Calendar.FRIDAY: cal.add(Calendar.DAY_OF_WEEK, inFuture ? 0 : -7); break; case Calendar.SATURDAY: cal.add(Calendar.DAY_OF_WEEK, inFuture ? 6 : -1); break; case Calendar.SUNDAY: cal.add(Calendar.DAY_OF_WEEK, inFuture ? 5 : -2); break; } return cal.getTime(); }
From source file:ca.mudar.parkcatcher.ui.fragments.DetailsFragment.java
@Override public boolean onOptionsItemSelected(MenuItem item) { final Resources res = getResources(); if (item.getItemId() == R.id.menu_favorites_toggle) { onCheckedChanged(mIsStarred);// ww w .ja v a2 s .co m mIsStarred = (mIsStarred ? false : true); // Toggle value getSherlockActivity().invalidateOptionsMenu(); return true; } else if (item.getItemId() == R.id.menu_map) { final Intent intent = new Intent(getActivity(), MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(Const.INTENT_EXTRA_GEO_LAT, mGeoLat); intent.putExtra(Const.INTENT_EXTRA_GEO_LNG, mGeoLng); intent.putExtra(Const.INTENT_EXTRA_POST_ID, mIdPost); startActivity(intent); return true; } else if (item.getItemId() == R.id.menu_reminder) { parkingApp.showToastText(R.string.toast_todo_reminder, Toast.LENGTH_LONG); return true; } else if (item.getItemId() == R.id.menu_directions) { if ((Double.compare(mGeoLat, Double.MIN_VALUE) != 0) && (Double.compare(mGeoLng, Double.MIN_VALUE) != 0)) { /** * Get directions using Intents. */ try { final Uri uriNavigation = Uri .parse(String.format(Const.URI_INTENT_NAVIGATION, mGeoLat, mGeoLng)); final Intent intent = new Intent(Intent.ACTION_VIEW, uriNavigation); startActivity(intent); } catch (Exception e) { e.printStackTrace(); String sAddr = ""; Location userLocation = parkingApp.getLocation(); if (userLocation != null) { sAddr = Double.toString(userLocation.getLatitude()) + "," + Double.toString(userLocation.getLongitude()); } final String urlGmaps = String.format(Const.URL_GMAPS_DIRECTIONS, sAddr, mGeoLat + "," + mGeoLng); final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlGmaps)); startActivity(intent); } } return true; } else if (item.getItemId() == R.id.menu_streetview) { if ((Double.compare(mGeoLat, Double.MIN_VALUE) != 0) && (Double.compare(mGeoLng, Double.MIN_VALUE) != 0)) { try { final Uri uriStreetView = Uri .parse(String.format(Const.URI_INTENT_STREETVIEW, mGeoLat, mGeoLng)); final Intent intent = new Intent(Intent.ACTION_VIEW, uriStreetView); startActivity(intent); } catch (NullPointerException e) { e.printStackTrace(); return false; } catch (Exception e) { parkingApp.showToastText(R.string.toast_streetview_error, Toast.LENGTH_LONG); e.printStackTrace(); final Uri uriInstallStreetView = Uri.parse(Const.URI_INSTALL_STREETVIEW); final Intent intent = new Intent(Intent.ACTION_VIEW, uriInstallStreetView); startActivity(intent); return false; } } return true; } else if (item.getItemId() == R.id.menu_share) { final GregorianCalendar parkingCalendar = parkingApp.getParkingCalendar(); final int dayOfWeek = (parkingCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ? 7 : parkingCalendar.get(Calendar.DAY_OF_WEEK) - 1); final double parkingHour = parkingCalendar.get(Calendar.HOUR_OF_DAY) + Math.round(parkingCalendar.get(Calendar.MINUTE) / 0.6) / 100.00d; // final int duration = parkingApp.getParkingDuration(); final String url = String.format(res.getString(R.string.url_share_post_id), mIdPost, dayOfWeek, parkingHour, parkingApp.getParkingDuration()); final String subject = String.format(res.getString(R.string.details_share_title), url); final String desc = String.format(res.getString(R.string.details_share_subtitle), mShareDesc); final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); // EXTRA_SUBJECT is not used to allow sharing with SMS instead of // MMS // intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, subject + Const.LINE_SEPARATOR + desc); startActivity(intent); return true; } return (activityHelper.onOptionsItemSelected(item) || super.onOptionsItemSelected(item)); }
From source file:org.energy_home.jemma.internal.ah.eh.esp.ESPHapServiceObject.java
private Float getFloatValueMonthlyForecast(AHContainerAddress dailyContainerId, AHContainerAddress wdHourlyAvgContainerId) throws M2MHapException { Calendar c = Calendar.getInstance(); long now = c.getTimeInMillis(); int todayDayOfWeek = c.get(Calendar.DAY_OF_WEEK); int todayMonth = c.get(Calendar.MONTH); int todayDayOfYear = c.get(Calendar.DAY_OF_YEAR); float currentMonthEstimation = 0; boolean useTodayEstimation = false; float todayEstimation = 0; long totalDuration = 0; long startTime = getNormalizedStartTime(c, now, ESPService.MONTH_RESOLUTION); long endTime = now; long lastTime = startTime; long lastDuration = 0; int todayEstimationFirstHour = 0; int todayEstimationLastHour = 0; ContentInstance ci = null;/*w w w . ja v a2 s. co m*/ Float lastValue = null; Float value = null; // Retrieves current month daily consumption and sum ContentInstanceItems items = getItemsWithHapCache(c, dailyContainerId, startTime, endTime, ESPService.DAY_RESOLUTION); if (items != null) { List<ContentInstance> resultList = items.getContentInstances(); if (resultList != null) { ContentInstance contentInstance = null; FloatDV floatDV = null; for (Iterator<ContentInstance> iterator = resultList.iterator(); iterator.hasNext();) { contentInstance = iterator.next(); floatDV = (FloatDV) contentInstance.getContent(); if (floatDV != null) { value = floatDV.getValue(); if (!iterator.hasNext()) { lastValue = value; lastTime = contentInstance.getId().longValue(); lastDuration = floatDV.getDuration(); } else if (value != null) { currentMonthEstimation += value.floatValue(); totalDuration += floatDV.getDuration(); } } } log.info("getFloatValueMonthlyForecast - current month daily consumption returned: monthTotal=" + currentMonthEstimation + ", monthTotalDuration=" + totalDuration + ", lastValue=" + lastValue + ", lastTime=" + lastTime + ", lastDuration=" + lastDuration); } } else { return null; } // Fix duration error for all daily measures but the last one long durationError = (lastTime - startTime) - totalDuration; if (totalDuration != 0 && durationError > DateUtils.MILLISEC_IN_ONE_HOUR) currentMonthEstimation += currentMonthEstimation * ((float) durationError) / (lastTime - startTime); // // If total error for daily measures is greater than max error // tolerance a null value is returned // totalDuration += lastDuration; // if ((now - startTime) > totalDuration*(1+DURATION_ERROR_TOLERANCE)) // return null; // If a partial estimation for today is available, use it current day // estimation if (lastDuration > 0 && lastTime >= getNormalizedStartTime(c, now, ESPService.DAY_RESOLUTION)) { c.setTimeInMillis(lastTime); todayEstimationFirstHour = c.get(Calendar.HOUR_OF_DAY); c.setTimeInMillis(lastTime + lastDuration); todayEstimationLastHour = c.get(Calendar.HOUR_OF_DAY) - 1; if (c.get(Calendar.DAY_OF_YEAR) != todayDayOfYear) todayEstimationLastHour = 23; int estimatedNrOfHours = todayEstimationLastHour - todayEstimationFirstHour + 1; if (estimatedNrOfHours > 0) { useTodayEstimation = true; // Fix last duration error todayEstimation = (lastValue / lastDuration) * estimatedNrOfHours * DateUtils.MILLISEC_IN_ONE_HOUR; } } // Calculate an estimation for the average consumption of each week day, // including today estimation float[] weekDayEstimation = { 0, 0, 0, 0, 0, 0, 0 }; weekDayEstimation[todayDayOfWeek - 1] = todayEstimation; ContentInstanceItems weekDayItems = getNormalizedWeekDayItems(wdHourlyAvgContainerId, getHourlyDayOfWeekStartIndex(Calendar.SUNDAY), getHourlyDayOfWeekEndIndex(Calendar.SATURDAY)); if (weekDayItems == null) { log.warn("getFloatValueMonthlyForecast - week day average consumption returned null items\n"); return null; } List<ContentInstance> weekDayItemList = weekDayItems.getContentInstances(); if (weekDayItemList == null || weekDayItemList.size() == 0) { log.warn( "getFloatValueMonthlyForecast - week day average consumption returned null or 0 sized item list\n"); return null; } log.info("getFloatValueMonthlyForecast - week day average consumption returned\n" + weekDayItems); int weekDayIndex = 1; int hourlyIndex = 0; int nrOfMissingAvgValues = 0; for (Iterator<ContentInstance> iterator = weekDayItemList.iterator(); iterator.hasNext();) { ci = (ContentInstance) iterator.next(); value = toFloat(ci); if (value != null && value.floatValue() >= 0) { if (!useTodayEstimation || weekDayIndex != todayDayOfWeek || (hourlyIndex < todayEstimationFirstHour || hourlyIndex > todayEstimationLastHour)) { weekDayEstimation[weekDayIndex - 1] += value.floatValue(); } } else { nrOfMissingAvgValues++; } hourlyIndex++; if (hourlyIndex % 24 == 0) { weekDayIndex++; hourlyIndex = 0; } } if (nrOfMissingAvgValues * DateUtils.MILLISEC_IN_ONE_HOUR >= DateUtils.MILLISEC_IN_ONE_DAY) { log.info("getFloatValueMonthlyForecast: too many average missing values - " + nrOfMissingAvgValues); return null; } else if (nrOfMissingAvgValues > 0) { log.info("getFloatValueMonthlyForecast: found some missing values - " + nrOfMissingAvgValues); } // The following update to lastTime value is necessary to manage legal // time switch c.setTimeInMillis(lastTime); c.set(Calendar.HOUR_OF_DAY, 12); lastTime = c.getTimeInMillis(); while (c.get(Calendar.MONTH) == todayMonth) { currentMonthEstimation += weekDayEstimation[c.get(Calendar.DAY_OF_WEEK) - 1]; lastTime += DateUtils.MILLISEC_IN_ONE_DAY; c.setTimeInMillis(lastTime); } return currentMonthEstimation * ((float) (weekDayItemList.size() + nrOfMissingAvgValues)) / weekDayItemList.size(); }
From source file:com.samsistemas.calendarview.widget.CalendarView.java
/** * This method init all necessary variables and Views that our Calendar is going to use. *//*from w w w.j a v a 2 s .co m*/ private void init() { mScroller = new Scroller(mContext, null); //Variables associated to handle touch events.. final ViewConfiguration configuration = ViewConfiguration.get(mContext); final float density = mContext.getResources().getDisplayMetrics().density; //Variables associated to Swipe.. mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density); mCloseEnough = (int) (CLOSE_ENOUGH * density); mDefaultGutterSize = (int) (DEFAULT_GUTTER_SIZE * density); //Inflate current view.. mView = LayoutInflater.from(mContext).inflate(R.layout.material_calendar_with_title, this, true); //Get buttons for Calendar and set its listeners.. mBackButton = (ImageView) mView.findViewById(R.id.left_button); mNextButton = (ImageView) mView.findViewById(R.id.right_button); mBackButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mCurrentMonthIndex--; mCalendar = Calendar.getInstance(Locale.getDefault()); mCalendar.add(Calendar.MONTH, mCurrentMonthIndex); refreshCalendar(mCalendar); if (mOnMonthChangedListener != null) { mOnMonthChangedListener.onMonthChanged(mCalendar.getTime()); } } }); mNextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mCurrentMonthIndex++; mCalendar = Calendar.getInstance(Locale.getDefault()); mCalendar.add(Calendar.MONTH, mCurrentMonthIndex); refreshCalendar(mCalendar); if (mOnMonthChangedListener != null) { mOnMonthChangedListener.onMonthChanged(mCalendar.getTime()); } } }); setFirstDayOfWeek(Calendar.SUNDAY); refreshCalendar(Calendar.getInstance(getLocale())); }