private long daysDiff(final Calendar today, final Calendar nextSeperatorDate) { Calendar date = (Calendar) today.clone(); date.set(Calendar.HOUR_OF_DAY, 0); date.set(Calendar.MINUTE, 0); date.set(Calendar.SECOND, 0); date.set(Calendar.MILLISECOND, 0); Calendar next = (Calendar) nextSeperatorDate.clone(); next.set(Calendar.HOUR_OF_DAY, 0); next.set(Calendar.MINUTE, 0); next.set(Calendar.SECOND, 0); next.set(Calendar.MILLISECOND, 0); long daysBetween = 0; int multi = 1; if (!date.before(next)) { if (date.compareTo(next) != 0) { multi = -1; Calendar temp = (Calendar) date.clone(); date = (Calendar) next.clone(); next = (Calendar) temp.clone(); } } while (date.before(next)) { date.add(Calendar.DAY_OF_MONTH, 1); daysBetween++; } return multi * daysBetween; }
public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage : java CalendarEx7 2004 11"); return; } int year = Integer.parseInt(args[0]); int month = Integer.parseInt(args[1]); Calendar sDay = Calendar.getInstance(); // 시작일 Calendar eDay = Calendar.getInstance(); // 끝일 // 월의 경우 0부터 11까지의 값을 가지므로 1을 빼줘야 한다. // 예를 들어, 2004년 11월 1일은 sDay.set(2004,10,1);과 같이 해줘야 한다. sDay.set(year, month - 1, 1); // 입력월의 1일로 설정 한다. // 입력 월의 말일로 설정한다. eDay.set(year, month - 1, sDay.getActualMaximum(Calendar.DATE)); // 1일이 속한 주의일요일로 날짜설정. sDay.add(Calendar.DATE, -sDay.get(Calendar.DAY_OF_WEEK) + 1); // 말일이 속한 주의 토요일로 날짜설정 eDay.add(Calendar.DATE, 7 - eDay.get(Calendar.DAY_OF_WEEK)); System.out.println(" " + year + "년 " + month + "월"); System.out.println(" SU MO TU WE TH FR SA"); // 시작일과 마지막일까지(sDay<=eDay) 1일씩 증가시켜가면서 일(Calendar.DATE)을 출력한다. for (int n = 1; sDay.before(eDay) || sDay.equals(eDay); sDay.add(Calendar.DATE, 1)) { int day = sDay.get(Calendar.DATE); System.out.print((day < 10) ? " " + day : " " + day); if (n++ % 7 == 0) { System.out.println(); // 7일치를 찍고 나서 죽을 바꾼다. } } } // main
private static boolean keepCurrent(Calendar asOfDate) { boolean keepCurrent = false; int monthNow = asOfDate.get(Calendar.MONTH); // March, June, September, and December are expiration months boolean isExpirationMonth = ((monthNow + 1) % 3 == 0); if (isExpirationMonth) { Calendar volumeShiftDate = (Calendar) asOfDate.clone(); // Find first Friday volumeShiftDate.set(Calendar.DAY_OF_MONTH, 1); while (volumeShiftDate.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY) { volumeShiftDate.add(Calendar.DAY_OF_MONTH, 1); } // Shift to third Friday volumeShiftDate.add(Calendar.WEEK_OF_MONTH, 2); // Finally, find the day before second Friday volumeShiftDate.add(Calendar.DAY_OF_MONTH, -8); if (asOfDate.before(volumeShiftDate)) { keepCurrent = true; } } return keepCurrent; }
/** * 给定阳历日期year年month月day日,返回从当前的日期开始,下一个出现month月day日的日期; 用于给定阳历出生日期,返回下一个生日日期; * * @param * @return 如果给定日期不小于当前的日期,返回给定的日期; * @exception * @see * @since */ public Calendar getNextSolarBirthday(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); Calendar next = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, -1); next.set(year, month - 1, day); if (next.before(calendar)) { // 阳历生日为2月29日 if (2 == month && 29 == day) { int BirthdayYear = calendar.get(Calendar.YEAR); // 获得下一个闰年。 while (!isSolarLeapYear(BirthdayYear)) { BirthdayYear++; } next.set(BirthdayYear, month - 1, day, 0, 0, 0); // 该生日已过去了 if (next.before(calendar)) { // 获得下一个闰年。 // do{ BirthdayYear += 4; // }while(!isSolarLeapYear(year)); next.set(Calendar.YEAR, BirthdayYear); } } else { next.set(calendar.get(Calendar.YEAR), month - 1, day, 0, 0, 0); if (next.before(calendar)) { next.add(Calendar.YEAR, 1); } } } return next; }
public Calendar addRecurring(Calendar c) { Calendar now = new GregorianCalendar(); if (isExact()) { c = now; } now.set(Calendar.SECOND, 0); now.add(Calendar.MINUTE, -1); List<Integer> weekdays = getWeekdays(); if (weekdays.size() == 0) { if ((getStartDate() == null || (getStartDate() != null && now.after(getStartDate()))) && (getEndDate() == null || (getEndDate() != null && now.before((getEndDate()))))) { do { c.add(Calendar.DAY_OF_MONTH, getDays()); c.add(Calendar.MONTH, getMonths()); c.add(Calendar.YEAR, getYears()); if (!isForDue()) { c.add(Calendar.MINUTE, getMinutes()); c.add(Calendar.HOUR, getHours()); } } while (c.before(now)); } } else { int diff = 8; if (c.compareTo(now) < 0) c = now; c.add(Calendar.DAY_OF_MONTH, 1); for (Integer day : weekdays) { int local_diff = day - c.get(Calendar.DAY_OF_WEEK); if (local_diff < 0) local_diff += 7; if (diff > local_diff) diff = local_diff; } c.add(Calendar.DAY_OF_MONTH, diff); } return c; }
/** * Worker method called by the retry processing timer. This checks any reliable messages that have * not yet had an acknowledgement (or explicit error) to see if they need retrying, or if they are * due for expiry. Any expired messages have the expiry process, including any user-supplied * expiry handler, called on them. * * <p>It also requests that the listener checks its de-duplication list against persist durations, * and clears out any message ids from that list that are out of scope. */ void processRetries() { if ((requests == null) || (requests.isEmpty())) { listener.cleanDeduplicationList(); return; } Calendar check = Calendar.getInstance(); ArrayList<Sendable> expires = new ArrayList<>(); for (Sendable s : requests.values()) { Calendar expiryTime = s.getStarted(); expiryTime.add(Calendar.SECOND, s.getPersistDuration()); if (expiryTime.before(check)) { expires.add(s); } else { Calendar retryAfter = s.lastTry(); if (retryAfter == null) return; retryAfter.add(Calendar.SECOND, s.getRetryInterval()); if (retryAfter.before(check)) { (new Transmitter(s)).start(); } } } for (Sendable s : expires) { try { removeRequest(s.getMessageId()); s.expire(); } catch (Exception e) { SpineToolsLogger.getInstance() .log("org.warlock.spine.connection.ConnectionManager.expireException", e); } } }
public short nextTimeIndex() { Calendar now = new GregorianCalendar(); if (now.before(schedule[CONSTANT.FAJR])) return CONSTANT.FAJR; for (short i = CONSTANT.FAJR; i < CONSTANT.NEXT_FAJR; i++) { if (now.after(schedule[i]) && now.before(schedule[i + 1])) { return ++i; } } return CONSTANT.NEXT_FAJR; }
/** * Updates the view list of available rooms * * @param checkIn check-in date * @param checkOut check-out date * @param type room type */ public void updateViewData(Calendar checkIn, Calendar checkOut, double type) { viewData.clear(); for (int i = 0; i < roomList.size(); i++) { // traverses roomList Room room = roomList.get(i); // <---room to be added to the available rooms list if (room.noReservations()) { viewData.add(roomList.get(i)); for (ChangeListener l : listeners) { l.stateChanged(new ChangeEvent(this)); } } else { // if a room has reservations, check each reservation for conflicting dates // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY"); boolean flag = false; for (int j = 0; j < room.reservations.size(); j++) { // traverses room's list of reservations Reservation r = room.reservations.get(j); if ((checkIn.before(r.checkInDate) || checkIn.after(r.checkOutDate)) && (checkOut.before(r.checkInDate) || checkOut.after(r.checkOutDate)) && (checkIn.compareTo(r.checkInDate) != 0 && checkOut.compareTo(r.checkOutDate) != 0)) { flag = true; // okay to add } else { flag = false; } } if (flag) { viewData.add(room); for (ChangeListener l : listeners) { l.stateChanged(new ChangeEvent(this)); } } } } if (type == 0) { viewData.clear(); } else { for (int k = 0; k < viewData.size(); k++) { double temp = viewData.get(k).getRate(); if (temp != type) { System.out.println("viewData rate: " + viewData.get(k).getRate()); System.out.println("Type: " + type); viewData.remove(k); } } for (ChangeListener l : listeners) { l.stateChanged(new ChangeEvent(this)); } } }
private boolean neededToRequestPushWooshServer(Context context) { Calendar nowTime = Calendar.getInstance(); Calendar tenMinutesBefore = Calendar.getInstance(); tenMinutesBefore.add(Calendar.MINUTE, -10); // decrement 10 minutes Calendar lastPushWooshRegistrationTime = Calendar.getInstance(); lastPushWooshRegistrationTime.setTime(new Date(PreferenceUtils.getLastRegistration(context))); if (tenMinutesBefore.before(lastPushWooshRegistrationTime) && lastPushWooshRegistrationTime.before(nowTime)) { // tenMinutesBefore <= lastPushWooshRegistrationTime <= nowTime return false; } return true; }
@Override public Location predictPath(Calendar cal) { Collections.sort(locations); if (cal == null) { return locations.get(0); } if (!cal.before(locations.get(0).getTime())) { // If there is only one location, use direction to predict new location if (locations.size() < 2) { double distance = (double) (cal.getTimeInMillis() - locations.get(0).getTime().getTimeInMillis()) / 1000 * speed; double dx = Math.cos(Math.toRadians(getDirection().toAngle())) * distance; double dy = Math.sin(Math.toRadians(getDirection().toAngle())) * distance; Location loc = locations.get(0); return new Location(loc.getX() + dx, loc.getY() + dy, cal); // With multiple locations available, use interpolation to predict new location } else { Location first = locations.get(1); Location second = locations.get(0); return Location.interpolate(first, second, cal); } } else { Location before = null; for (Location loc : locations) { if (!cal.before((Calendar) loc.getTime())) { before = loc; break; } } Location after = null; for (Location loc : locations) { if (!cal.after((Calendar) loc.getTime())) { after = loc; } } if (before == null) { return locations.getLast(); } else { return Location.interpolate(before, after, cal); } } }
/** * Returns {@code true} if the end date occurs after the start date during the period of time * represented by this time span. * * @param mutableStartDate a <i>mutable<i> {@code Calendar} object that will be changed to the * ending time of this time range as a side effect of this method */ private boolean isInRange(Calendar mutableStartDate, Calendar endDate) { // ensure that the ending date does not occur before the time span would // have started if (endDate.before(mutableStartDate)) return false; // update the start date to be the date at the end of the time span Calendar tsEnd = mutableStartDate; tsEnd.add(Calendar.YEAR, years); tsEnd.add(Calendar.MONTH, months); tsEnd.add(Calendar.WEEK_OF_YEAR, weeks); tsEnd.add(Calendar.DAY_OF_YEAR, days); tsEnd.add(Calendar.HOUR, hours); return endDate.before(tsEnd); }
public boolean isRequestedAppearanceDateBetweenDates(Calendar startDate, Calendar endDate) { if (requestedAppearanceDate == null || (startDate == null && endDate == null)) { return false; } Calendar requestedAppearanceCalendar = DateUtils.clearTimeFromCalendar(DateUtils.toCalendar(requestedAppearanceDate)); if (endDate != null) { return !requestedAppearanceCalendar.before(startDate) && !endDate.before(requestedAppearanceCalendar); } return startDate.equals(requestedAppearanceCalendar); }
private void accessBusinessCheck(UploadRequestUrl requestUrl, String password) throws BusinessException { UploadRequest request = requestUrl.getUploadRequest(); if (!isValidPassword(requestUrl, password)) { throw new BusinessException( BusinessErrorCode.UPLOAD_REQUEST_URL_FORBIDDEN, "You do not have the right to get this upload request url : " + requestUrl.getUuid()); } if (!(request.getStatus().equals(UploadRequestStatus.STATUS_ENABLED) || request.getStatus().equals(UploadRequestStatus.STATUS_CLOSED))) { throw new BusinessException( BusinessErrorCode.UPLOAD_REQUEST_READONLY_MODE, "The current upload request url is not available : " + requestUrl.getUuid()); } Calendar now = GregorianCalendar.getInstance(); Calendar compare = GregorianCalendar.getInstance(); compare.setTime(request.getActivationDate()); if (now.before(compare)) { throw new BusinessException( BusinessErrorCode.UPLOAD_REQUEST_NOT_ENABLE_YET, "The current upload request url is not enable yet : " + requestUrl.getUuid()); } compare.setTime(request.getExpiryDate()); if (now.after(compare)) { throw new BusinessException( BusinessErrorCode.UPLOAD_REQUEST_NOT_ENABLE_YET, "The current upload request url is no more available now. : " + requestUrl.getUuid()); } }
public static List<Date[]> getDays(Date from, Date to) { List<Date[]> list = new ArrayList<Date[]>(); Date[] fromto; Calendar c = Calendar.getInstance(); c.setTime(from); Calendar cTo = Calendar.getInstance(); cTo.setTime(to); /*fromto = new Date[2]; fromto[0] = c.getTime(); fromto[1] = cTo.getTime(); list.add(fromto); return list;*/ while (c.before(cTo)) { if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY || c.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) { Date lFrom = c.getTime(); Calendar lCal = Calendar.getInstance(); lCal.setTime(lFrom); lCal.add(Calendar.DAY_OF_YEAR, 2); Date lTo = lCal.getTime(); fromto = new Date[2]; fromto[0] = lFrom; fromto[1] = lTo; list.add(fromto); } c.add(Calendar.DAY_OF_YEAR, 1); } return list; }
public void updateGameList() throws RemoteException, InvalidSessionException { final String user = usrMgr.getSession().getUser(); final ArrayList<GameInfo> fullList = srvAdapter.fetchGameList(usrMgr.getSession()); final ArrayList<GameInfo> currentList = new ArrayList<GameInfo>(); final ArrayList<GameInfo> openList = new ArrayList<GameInfo>(); final Calendar now = Calendar.getInstance(); final Calendar now2h = Calendar.getInstance(); now2h.add(Calendar.HOUR, -2); for (final GameInfo info : fullList) { if (info.getPlayers().contains(user)) { for (final Calendar c : info.getGameSessions()) { if (c.before(now) && c.after(now2h)) { currentList.add(info); break; } } } else if (info.getnFreeTerritories() > 0) { for (final Calendar c : info.getGameSessions()) { if (c.after(now2h)) { openList.add(info); break; } } } } mCurrentGameListModel.setData(currentList); mOpenGameListModel.setData(openList); }
public int compare(Object x, Object y) { Calendar xcal = (Calendar) x; Calendar ycal = (Calendar) y; if (xcal.before(ycal)) return -1; if (xcal.after(ycal)) return 1; return 0; }
public void setBornDate(String bornDateString) { Pattern p = Pattern.compile("^([0-9]{4})-([0-9]{2})-([0-9]{2})$"); Matcher m = p.matcher(bornDateString); if (m.matches()) { int year = Integer.valueOf(m.group(1)); int month = Integer.valueOf(m.group(2)) - 1; int day = Integer.valueOf(m.group(3)); bornDate = new GregorianCalendar(year, month, day).getTime(); Calendar nowCalendar = Calendar.getInstance(); nowCalendar.set(Calendar.HOUR_OF_DAY, 0); nowCalendar.set(Calendar.MINUTE, 0); nowCalendar.set(Calendar.SECOND, 0); nowCalendar.set(Calendar.MILLISECOND, 0); int yearNow = nowCalendar.get(Calendar.YEAR); Calendar nextBirthdayCalendar = new GregorianCalendar(yearNow, month, day); if (nextBirthdayCalendar.before(nowCalendar)) nextBirthdayCalendar.add(Calendar.YEAR, 1); nextBirthdayDate = nextBirthdayCalendar.getTime(); nextBirthdayInDays = (nextBirthdayCalendar.getTimeInMillis() - nowCalendar.getTimeInMillis()) / 86400000; } else { bornDate = null; nextBirthdayDate = null; nextBirthdayInDays = 0; } }
@RequestMapping( value = {"/", "/welcome**"}, method = RequestMethod.GET) public ModelAndView defaultPage() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); ModelAndView model = new ModelAndView(); if (!(auth instanceof AnonymousAuthenticationToken)) { UserDetails userDetail = (UserDetails) auth.getPrincipal(); model.addObject("nextBeers", nextBeerDAO.getBeers(userDetail.getUsername())); model.addObject( "hasBeersWithoutDate", nextBeerDAO.hasBeersWithoutDate(userDetail.getUsername())); model.setViewName("homeLogged"); } else { model.setViewName("home"); } NextBeer nextestBeer = nextBeerDAO.getNextBeer(); Calendar today = Calendar.getInstance(); today.set(Calendar.HOUR_OF_DAY, 23); today.set(Calendar.MINUTE, 59); if (nextestBeer != null && today.before(nextestBeer.getDateToPay())) { model.addObject("dateToPayNextBeers", nextestBeer.getDateToPay()); } model.addObject("allNextBeers", nextBeerDAO.getAllNextBeers()); return model; }
private static StartTimeDetails createStartTimeDetails( final UUID devUUID, long timestamp, MieleDeviceHomeBusDataREST dev) { StartTimeDetails startDetails = new StartTimeDetails(devUUID, timestamp); startDetails.setStartTime(-1); if (dev.getDeviceDetails() != null) { MieleDuration mieleStartTime = dev.getDeviceDetails().getStartTime(); if (mieleStartTime != null) { int starttime = mieleStartTime.duration(); if (starttime >= 0) { Calendar calNow = Calendar.getInstance(); Calendar calStartTime = (Calendar) calNow.clone(); calStartTime.set(Calendar.MINUTE, starttime % 60); calStartTime.set(Calendar.HOUR_OF_DAY, starttime / 60); if (calStartTime.before(calNow)) { calStartTime.add(Calendar.DAY_OF_YEAR, 1); } startDetails.setStartTime(calStartTime.getTimeInMillis() / 1000L); } } } return startDetails; }
/** * Called at start-up if the system needs to load any persisted, reliable messages for sending. * This applies the persist duration for the message type to the declared timestamp and will run * the expire() method on anything that has expired whilst the MHS was down. * * @throws Exception */ public void loadPersistedMessages() throws Exception { if (ConditionalCompilationControls.TESTHARNESS) return; File d = new File(messageDirectory); File[] messages = d.listFiles(); EbXmlMessage ebxml = null; for (File f : messages) { try (FileInputStream fis = new FileInputStream(f)) { ebxml = new EbXmlMessage(fis); } catch (Exception e) { // TODO: Log failed attempt to get persisted message continue; } // See if we need to expire it // Calendar check = Calendar.getInstance(); Calendar expiryTime = ebxml.getStarted(); Long pd = persistDurations.get(ebxml.getHeader().getSvcIA()); int p = 0; if (pd != null) p = pd.intValue(); expiryTime.add(Calendar.SECOND, p); if (expiryTime.before(check)) { depersist(ebxml.getMessageId()); ebxml.expire(); } else { // Add it to requests requests.put(ebxml.getMessageId(), ebxml); } } }
@Deprecated public boolean isActive() { Calendar in4Months = Calendar.getInstance(); in4Months.add(Calendar.MONTH, 4); return submissionDeadline.before(in4Months); }
/** 根据用户生日计算年龄 */ public static int getAgeByBirthday(Date birthday) { Calendar cal = Calendar.getInstance(); if (cal.before(birthday)) { throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!"); } int yearNow = cal.get(Calendar.YEAR); int monthNow = cal.get(Calendar.MONTH) + 1; int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); cal.setTime(birthday); int yearBirth = cal.get(Calendar.YEAR); int monthBirth = cal.get(Calendar.MONTH) + 1; int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); int age = yearNow - yearBirth; if (monthNow <= monthBirth) { if (monthNow == monthBirth) { // monthNow==monthBirth if (dayOfMonthNow < dayOfMonthBirth) { age--; } } else { // monthNow>monthBirth age--; } } return age; }
public Tyopaiva(Calendar alku, Calendar loppu) { this.aikaMuoto = new SimpleDateFormat("dd-MM-yyyy HH:mm"); this.alku = alku; this.loppu = loppu; if (loppu.before(alku)) {} }
public boolean validareditado(int row) { String inicio = jTable1.getValueAt(row, 1).toString(); String fin = jTable1.getValueAt(row, 2).toString(); String[] ainicio = inicio.split(","); String[] afin = fin.split(","); if (Integer.parseInt(ainicio[0]) < 24 && Integer.parseInt(afin[0]) < 24 && Integer.parseInt(afin[0]) >= 0 && Integer.parseInt(ainicio[0]) >= 0) { if (Integer.parseInt(ainicio[1]) < 60 && Integer.parseInt(afin[1]) < 60 && Integer.parseInt(afin[1]) >= 0 && Integer.parseInt(ainicio[1]) >= 0) { if (Integer.parseInt(ainicio[2]) < 60 && Integer.parseInt(afin[2]) < 60 && Integer.parseInt(afin[2]) >= 0 && Integer.parseInt(ainicio[2]) >= 0) { Calendar ca = Calendar.getInstance(); Calendar ca2 = Calendar.getInstance(); ca.set(Calendar.HOUR_OF_DAY, Integer.parseInt(ainicio[0])); ca.set(Calendar.MINUTE, Integer.parseInt(ainicio[1])); ca.set(Calendar.SECOND, Integer.parseInt(ainicio[2])); ca2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(afin[0])); ca2.set(Calendar.MINUTE, Integer.parseInt(afin[1])); ca2.set(Calendar.SECOND, Integer.parseInt(afin[2])); if (ca.before(ca2)) { return true; } } } } JOptionPane.showMessageDialog(null, "ERROR al respetar el formato"); return false; }
public int findAllBirthsBetweenIntervalByGender(Calendar startDate, Calendar endDate, int flag) { int count = 0; List<PregnancyOutcome> outcomes = genericDao.findAll(PregnancyOutcome.class, true); for (PregnancyOutcome outcome : outcomes) { Calendar outcomeDate = outcome.getOutcomeDate(); if ((outcomeDate.after(startDate) || outcomeDate.equals(startDate)) && (outcomeDate.before(endDate))) { List<Outcome> allOutcomes = outcome.getOutcomes(); for (Outcome o : allOutcomes) { if (o.getType().equals(siteProperties.getLiveBirthCode())) { // male if (flag == 0) { if (o.getChild().getGender().equals(siteProperties.getMaleCode())) { if (o.getType().equals(siteProperties.getLiveBirthCode())) { count++; } } } // female else { if (o.getChild().getGender().equals(siteProperties.getFemaleCode())) { if (o.getType().equals(siteProperties.getLiveBirthCode())) { count++; } } } } } } } return count; }
@Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub Calendar today = Calendar.getInstance(); // today.set(Calendar.HOUR, 0); // today.set(Calendar.MINUTE, 0); // today.set(Calendar.SECOND ,0); Calendar setDate = Calendar.getInstance(); setDate.set(Calendar.YEAR, year); setDate.set(Calendar.MONTH, monthOfYear); setDate.set(Calendar.DATE, dayOfMonth); if (setDate.before(today)) { makeToast("Schedule date should be greater or equal to the present date."); return; } else { // edtSignupBday.setText(year + "-" + (monthOfYear + 1) + "-"+ dayOfMonth); schedule.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year); } }
/** Returns a new Calendar object which is between start and end */ public static Calendar rand(Calendar start, Calendar end) { if (start.after(end)) { Calendar temp = start; start = end; end = temp; } long diff = end.getTime().getTime() - start.getTime().getTime(); long daysDiff = diff / (1000 * 60 * 60 * 24); int delta = rand(0, (int) daysDiff); Calendar newCal = Calendar.getInstance(); newCal.setTime(start.getTime()); newCal.setTimeZone(start.getTimeZone()); newCal.add(Calendar.DAY_OF_MONTH, delta); newCal.add(Calendar.HOUR, rand(0, 23)); newCal.add(Calendar.MINUTE, rand(0, 59)); newCal.add(Calendar.SECOND, rand(0, 59)); // check range cause we might random picked value // greater than the range. if (newCal.after(end)) { newCal.setTime(end.getTime()); newCal.setTimeZone(end.getTimeZone()); } if (newCal.before(start)) { newCal.setTime(start.getTime()); newCal.setTimeZone(start.getTimeZone()); } return newCal; }
/**根据数据范围计算时间轴刻度 * <pre> * 单位刻度:一天 * 最多刻度数量:7个 * <1天:(step:1)0,1 * <=7天:(step:1)1,2,3,4,5,6,7 * 8天:(step:2)1,3,5,7,9 * 29天:(step:5)1,6,11,16,21,26,31 * >月:(月) * 3个月:(step:15)1,16,31,56,71,96,111 或者(step:月):1,2,3 * 大于年:(step:n年) * * * @param start 数据起始位置 * @param end 数据结束位置 * @param scaleBase 单位刻度 * @param isRound 边缘是否按整刻度 * @param maxScales 最多刻度数量 * @return */ public static long[] getListTime_scale( long start, long end, long scaleBase, boolean isRound, int maxScales) { long datas[]; long dataArea = end - start; int stepField = getDateField(dataArea); long step = (dataArea) / maxScales; if (step < scaleBase) { step = scaleBase; } long fieldValue = getDateFieldInMillis(stepField); step = (step + fieldValue - 1) / fieldValue; datas = new long[(int) ((dataArea + fieldValue * step - 1) / (fieldValue * step))]; // System.out.println("stepField "+ stepField+" fieldValue " +fieldValue+ " step: "+step); Calendar fromCalendar = Calendar.getInstance(); Calendar toCalcendar = Calendar.getInstance(); fromCalendar.setTimeInMillis(start); toCalcendar.setTimeInMillis(end); for (int i = 0; fromCalendar.before(toCalcendar); ++i, fromCalendar.set(stepField, (int) (fromCalendar.get(stepField) + step))) { datas[i] = fromCalendar.getTimeInMillis(); // System.out.println(formatter.format(fromCalendar.getTimeInMillis())); } // System.out.println("date:"+formatter.format(fromCalendar.getTimeInMillis())); return datas; }
public static boolean checkDate(String date1, String date2) { Date date11 = DateUtil.str2Date(date1, "yyyy-MM-dd HH:mm:ss"); // 起始时间 Date date22 = DateUtil.str2Date(date2, "yyyy-MM-dd HH:mm:ss"); // 终止时间 Calendar scalendar = Calendar.getInstance(); scalendar.setTime(date11); // 起始时间 Calendar ecalendar = Calendar.getInstance(); ecalendar.setTime(date22); // 终止时间 Calendar calendarnow = Calendar.getInstance(); System.out.println(date11.toString()); System.out.println(date22.toString()); System.out.println(scalendar.toString()); System.out.println(ecalendar.toString()); System.out.println(calendarnow.toString()); if (calendarnow.after(scalendar) && calendarnow.before(ecalendar)) { return true; } else { return false; } }
/** * Fix and update all alarm instance when a time change event occurs. * * @param context application context */ public static void fixAlarmInstances(Context context) { // Register all instances after major time changes or when phone restarts final ContentResolver contentResolver = context.getContentResolver(); final Calendar currentTime = getCurrentTime(); for (AlarmInstance instance : AlarmInstance.getInstances(contentResolver, null)) { final Alarm alarm = Alarm.getAlarm(contentResolver, instance.mAlarmId); final Calendar priorAlarmTime = alarm.getPreviousAlarmTime(instance.getAlarmTime()); final Calendar missedTTLTime = instance.getMissedTimeToLive(); if (currentTime.before(priorAlarmTime) || currentTime.after(missedTTLTime)) { final Calendar oldAlarmTime = instance.getAlarmTime(); final Calendar newAlarmTime = alarm.getNextAlarmTime(currentTime); final CharSequence oldTime = DateFormat.format("MM/dd/yyyy hh:mm a", oldAlarmTime); final CharSequence newTime = DateFormat.format("MM/dd/yyyy hh:mm a", newAlarmTime); LogUtils.i( "A time change has caused an existing alarm scheduled to fire at %s to" + " be replaced by a new alarm scheduled to fire at %s", oldTime, newTime); // The time change is so dramatic the AlarmInstance doesn't make any sense; // remove it and schedule the new appropriate instance. AlarmStateManager.setDismissState(context, instance); } else { registerInstance(context, instance, false); } } updateNextAlarm(context); }