Java Code Examples for java.util.Calendar#after()

The following examples show how to use java.util.Calendar#after() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RangerValidityScheduleEvaluator.java    From ranger with Apache License 2.0 6 votes vote down vote up
private Calendar getEarlierCalendar(Calendar dayOfMonthCalendar, Calendar dayOfWeekCalendar) throws Exception {

            Calendar withDayOfMonth = fillOutCalendar(dayOfMonthCalendar);
            if (LOG.isDebugEnabled()) {
                LOG.debug("dayOfMonthCalendar:[" + (withDayOfMonth != null ? withDayOfMonth.getTime() : null) + "]");
            }

            Calendar withDayOfWeek = fillOutCalendar(dayOfWeekCalendar);
            if (LOG.isDebugEnabled()) {
                LOG.debug("dayOfWeekCalendar:[" + (withDayOfWeek != null ? withDayOfWeek.getTime() : null) + "]");
            }

            if (withDayOfMonth != null && withDayOfWeek != null) {
                return withDayOfMonth.after(withDayOfWeek) ? withDayOfMonth : withDayOfWeek;
            } else if (withDayOfMonth == null) {
                return withDayOfWeek;
            } else {
                return withDayOfMonth;
            }
        }
 
Example 2
Source File: SunriseSunset.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
/**
 * @param calendar  a datetime
 * @param latitude  the latitude of the location in degrees.
 * @param longitude the longitude of the location in degrees (West is negative)
 * @return true if it is night at the given location and datetime. This returns
 * true if the given datetime at the location is after the astronomical twilight dusk and before
 * the astronomical twilight dawn.
 */
public static boolean isNight(Calendar calendar, double latitude, double longitude) {
    Calendar[] astronomicalTwilight = getAstronomicalTwilight(calendar, latitude, longitude);
    if (astronomicalTwilight == null) {
        int month = calendar.get(Calendar.MONTH); // Reminder: January = 0
        if (latitude > 0) {
            if (month >= 3 && month <= 10) {
                return false; // Always day at the north pole in June
            } else {
                return true; // Always night at the north pole in December
            }
        } else {
            if (month >= 3 && month <= 10) {
                return true; // Always night at the south pole in June
            } else {
                return false; // Always day at the south pole in December
            }
        }
    }
    Calendar dawn = astronomicalTwilight[0];
    Calendar dusk = astronomicalTwilight[1];
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
    format.setTimeZone(calendar.getTimeZone());
    return calendar.before(dawn) || calendar.after(dusk);
}
 
Example 3
Source File: CustomPlaybackOverlayFragment.java    From jellyfin-androidtv with GNU General Public License v2.0 6 votes vote down vote up
public void showGuide() {
    hide();
    mPlaybackController.mVideoManager.contractVideo(Utils.convertDpToPixel(mActivity, 300));
    mTvGuide.setVisibility(View.VISIBLE);
    mGuideVisible = true;
    Calendar now = Calendar.getInstance();
    boolean needLoad = mCurrentGuideStart == null;
    if (!needLoad) {
        Calendar needLoadTime = (Calendar) mCurrentGuideStart.clone();
        needLoadTime.add(Calendar.MINUTE, 30);
        needLoad = now.after(needLoadTime);
    }
    if (needLoad) {
        loadGuide();
    }
}
 
Example 4
Source File: CalendarDateCalculator.java    From objectlabkit with Apache License 2.0 6 votes vote down vote up
@Override
public int getNumberOfBusinessDaysBetween(final Calendar d1, final Calendar d2) {
    if (d1 == null || d2 == null) {
        return 0;
    }
    final boolean d1B4d2 = !d1.after(d2);
    Calendar start = d1B4d2 ? d1 : d2;
    final Calendar end = d1B4d2 ? d2 : d1;
    if (getHolidayHandler() != null) {
        start = getHolidayHandler().adjustDate(start, 1, this);
    }

    int count = 0;

    while (start.before(end)) {
        if (!isNonWorkingDay(start)) {
            count++;
        }
        start.add(Calendar.DATE, 1);
    }
    return d1B4d2 ? count : -count;
}
 
Example 5
Source File: DateTimeUtils.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Applies the config to the given calendar.
 */
public static Calendar applyConfig(Calendar cal, AstroChannelConfig config) {
    Calendar cCal = cal;
    if (config.getOffset() != null && config.getOffset() != 0) {
        Calendar cOffset = Calendar.getInstance();
        cOffset.setTime(cCal.getTime());
        cOffset.add(Calendar.MINUTE, config.getOffset());
        cCal = cOffset;
    }

    Calendar cEarliest = adjustTime(cCal, getMinutesFromTime(config.getEarliest()));
    if (cCal.before(cEarliest)) {
        return cEarliest;
    }
    Calendar cLatest = adjustTime(cCal, getMinutesFromTime(config.getLatest()));
    if (cCal.after(cLatest)) {
        return cLatest;
    }

    return cCal;
}
 
Example 6
Source File: RuleImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
/**
 * This returns true is the rule is effective.
 * If the rule is not effective, it cannot activate.
 *
 * This uses the dateEffective, dateExpires and enabled flag to decide this.
 */
public boolean isEffective(Tuple tuple,
                           RuleTerminalNode rtn,
                           WorkingMemory workingMemory) {
    if ( !this.enabled.getValue( tuple,
                                 rtn.getEnabledDeclarations(),
                                 this,
                                 workingMemory ) ) {
        return false;
    }
    if ( this.dateEffective == null && this.dateExpires == null ) {
        return true;
    } else {
        Calendar now = Calendar.getInstance();
        now.setTimeInMillis( workingMemory.getSessionClock().getCurrentTime() );

        if ( this.dateEffective != null && this.dateExpires != null ) {
            return (now.after( this.dateEffective ) && now.before( this.dateExpires ));
        } else if ( this.dateEffective != null ) {
            return (now.after( this.dateEffective ));
        } else {
            return (now.before( this.dateExpires ));
        }
    }
}
 
Example 7
Source File: JcrPackageDefinitionImpl.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean isModified() {
    if (!isUnwrapped()) {
        return false;
    }
    Calendar mod = getLastModified();
    if (mod == null) {
        return false;
    }
    Calendar uw = getLastWrapped();
    if (uw == null) {
        uw = getLastUnwrapped();
    }
    if (uw == null) {
        // backward compat check
        try {
            if (defNode.hasProperty("unwrapped")) {
                return true;
            }
        } catch (RepositoryException e) {
            log.warn("Error while checking unwrapped property", e);
        }
        return false;
    }
    return mod.after(uw);
}
 
Example 8
Source File: SunLayout_1x1_1.java    From SuntimesWidget with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void updateViews(Context context, int appWidgetId, RemoteViews views, SuntimesRiseSetData data)
{
    super.updateViews(context, appWidgetId, views, data);
    boolean showSeconds = WidgetSettings.loadShowSecondsPref(context, appWidgetId);
    WidgetSettings.RiseSetOrder order = WidgetSettings.loadRiseSetOrderPref(context, appWidgetId);

    Calendar event = data.sunriseCalendar(1);
    if (order != WidgetSettings.RiseSetOrder.TODAY)
    {
        Calendar now = Calendar.getInstance();
        if (now.after(event)) {
            event = data.sunriseCalendar(2);
        }
    }
    updateViewsSunriseText(context, views, event, showSeconds);
}
 
Example 9
Source File: CloudUtil.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
public static String formatCommitDate(long value) {
	Calendar today = Calendar.getInstance();
	Calendar cal = Calendar.getInstance();
	cal.setTimeInMillis(value);
	if (cal.after(today))
		return "In future";
	int seconds = getDifference(today, cal, Calendar.SECOND, 60);
	if (seconds < 60)
		return timeText(seconds, "second");
	int minutes = getDifference(today, cal, Calendar.MINUTE, 60);
	if (minutes < 60)
		return timeText(minutes, "minute");
	int hours = getDifference(today, cal, Calendar.HOUR_OF_DAY, 24);
	if (hours < 24)
		return timeText(hours, "hour");
	int days = getDifference(today, cal, Calendar.DAY_OF_MONTH, 365);
	if (days < 7)
		return timeText(days, "day");
	if (days < 31)
		return timeText(days / 7, "week");
	int months = getDifference(today, cal, Calendar.MONTH, 12);
	if (days < 365 && months > 0)
		return timeText(months, "month");
	int years = Calendar.getInstance().get(Calendar.YEAR) - cal.get(Calendar.YEAR);
	return timeText(years, "year");
}
 
Example 10
Source File: ScheduleEvent.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public Transition nextTransition(Calendar from) {
   for(Transition transition : transitions()) {
      Calendar c = CalendarUtil.setTime(from, transition.timeOfDay());
      if(c.after(from)) {
         return Transition.builder(transition).withStartTime(c.getTime()).build();
      }
   }

   return null;
}
 
Example 11
Source File: DurationHelper.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
private Calendar getDateAfterRepeat(Calendar date) {
	Calendar current = TimeZoneUtil.convertToTimeZone(start, date.getTimeZone());
	
	if (repeatWithNoBounds) {
		
    while(current.before(date) || current.equals(date)) { // As long as current date is not past the engine date, we keep looping
    	Calendar newTime = add(current, period);
      if (newTime.equals(current) || newTime.before(current)) {
      	break;
      }
      current = newTime;
    }
    
		
	} else {
		
   int maxLoops = times;
   if (maxIterations > 0) {
     maxLoops = maxIterations - times;
   }
   for (int i = 0; i < maxLoops+1 && !current.after(date); i++) {
     current = add(current, period);
   }
	
	}
	return current.before(date) ? date : TimeZoneUtil.convertToTimeZone(current, clockReader.getCurrentTimeZone());
	
}
 
Example 12
Source File: DurationHelper.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private Calendar getDateAfterRepeat(Calendar date) {
    Calendar current = TimeZoneUtil.convertToTimeZone(start, date.getTimeZone());

    if (repeatWithNoBounds) {

        while (current.before(date) || current.equals(date)) { // As long as current date is not past the engine date, we keep looping
            Calendar newTime = add(current, period);
            if (newTime.equals(current) || newTime.before(current)) {
                break;
            }
            current = newTime;
        }

    } else {

        int maxLoops = times;
        if (maxIterations > 0) {
            maxLoops = maxIterations - times;
        }
        for (int i = 0; i < maxLoops + 1 && !current.after(date); i++) {
            current = add(current, period);
        }

    }
    return current.before(date) ? date : TimeZoneUtil.convertToTimeZone(current, clockReader.getCurrentTimeZone());

}
 
Example 13
Source File: SunriseSunset.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
/**
 * @param calendar the datetime for which to determine if it's civil twilight in the given location
 * @param latitude  the latitude of the location in degrees.
 * @param longitude the longitude of the location in degrees (West is negative)
 * @return true if it is civil twilight at the given location and the given calendar.
 * This returns true if the given time at the location is between sunset and civil twilight dusk
 * or between civil twilight dawn and sunrise.
 */
public static boolean isCivilTwilight(Calendar calendar, double latitude, double longitude) {
    Calendar[] sunriseSunset = getSunriseSunset(calendar, latitude, longitude);
    if (sunriseSunset == null) return false;
    Calendar[] civilTwilight = getCivilTwilight(calendar, latitude, longitude);
    if (civilTwilight == null) return false;

    return (calendar.after(sunriseSunset[1]) && calendar.before(civilTwilight[1])
            || (calendar.after(civilTwilight[0]) && calendar.before(sunriseSunset[0])));
}
 
Example 14
Source File: MoonPhasesView.java    From SuntimesWidget with GNU General Public License v3.0 5 votes vote down vote up
public void updateField(Context context, Calendar now, Calendar dateTime, boolean showWeeks, boolean showTime, boolean showHours, boolean showSeconds)
{
    if (field != null)
    {
        field.setText(utils.calendarDateTimeDisplayString(context, dateTime, showTime, showSeconds).getValue());
    }

    if (note != null)
    {
        String noteText = (dateTime == null ? "" : utils.timeDeltaDisplayString(now.getTime(), dateTime.getTime(), showWeeks, showHours).toString());
        String noteString = now.after(dateTime) ? context.getString(R.string.ago, noteText) : context.getString(R.string.hence, noteText);
        note.setText(SuntimesUtils.createBoldColorSpan(null, noteString, noteText, noteColor));
        note.setVisibility(View.VISIBLE);
    }
}
 
Example 15
Source File: EventTimerTask.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
	
	Calendar cal = EventTimer.getCalendarInServerTimeZone();
	
	for (EventTimer timer : EventTimer.timers.values()) {
		
		if (cal.after(timer.getNext())) {
			timer.setLast(cal);

			Calendar next;
			try {
				next = timer.getEventFunction().getNextDate();
			} catch (InvalidConfiguration e) {
				e.printStackTrace();
				continue;
			}
			
			if (next == null) {
				CivLog.warning("WARNING timer:"+timer.getName()+" did not return a next time.");
				continue;
			}

			timer.setNext(next);
			timer.save();

			timer.getEventFunction().process();
		}
		
	}
	
}
 
Example 16
Source File: DateUtilsBasic.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 建议改名, 实现有错 判断时间1是否在时间2之前.
 * @param date1
 *            String 类型的时间1 格式为"yyyy-mm-dd"
 * @param date2
 *            String 类型的时间1 格式为"yyyy-mm-dd"
 * @return boolean
 * 			  ture: date2 > date 1; false: date2 <= date1
 */
public static boolean getCompareResult(String date1, String date2) {
	Calendar calendar1 = Calendar.getInstance();
	calendar1.setTime(strToDate(date1));
	Calendar calendar2 = Calendar.getInstance();
	calendar2.setTime(strToDate(date2));
	if (calendar2.after(calendar1)) {
		return true;
	}
	return false;
}
 
Example 17
Source File: SunriseSunset.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
/**
 * @param calendar the datetime for which to determine if it's nautical twilight in the given location
 * @param latitude  the latitude of the location in degrees.
 * @param longitude the longitude of the location in degrees (West is negative)
 * @return true if it is nautical twilight at the given location and the given calendar.
 * This returns true if the given time at the location is between civil and nautical twilight dusk
 * or between nautical and civil twilight dawn.
 */
public static boolean isNauticalTwilight(Calendar calendar, double latitude, double longitude) {
    Calendar[] civilTwilight = getCivilTwilight(calendar, latitude, longitude);
    if (civilTwilight == null) return false;
    Calendar[] nauticalTwilight = getNauticalTwilight(calendar, latitude, longitude);
    if (nauticalTwilight == null) return false;

    return (calendar.after(civilTwilight[1]) && calendar.before(nauticalTwilight[1])
            || (calendar.after(nauticalTwilight[0]) && calendar.before(civilTwilight[0])));
}
 
Example 18
Source File: AzkabanAjaxAPIClient.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/***
 * Generate a random scheduled time between specified execution time window in the Azkaban compatible format
 * which is: hh,mm,a,z Eg. ScheduleTime=12,00,PM,PDT
 *
 * @param windowStartHour Window start hour in 24 hr (HH) format (inclusive)
 * @param windowEndHour Window end hour in 24 hr (HH) format (exclusive)
 * @param delayMinutes If current time is within window, then additional delay for bootstrapping if desired
 * @return Scheduled time string of the format hh,mm,a,z
 */
@edu.umd.cs.findbugs.annotations.SuppressWarnings(
    value = "DMI_RANDOM_USED_ONLY_ONCE",
    justification = "As expected for randomization")
public static String getScheduledTimeInAzkabanFormat(int windowStartHour, int windowEndHour, int delayMinutes) {
  // Validate
  if (windowStartHour < 0 || windowEndHour > 23 || windowStartHour >= windowEndHour) {
    throw new IllegalArgumentException("Window start should be less than window end, and both should be between "
        + "0 and 23");
  }
  if (delayMinutes < 0 || delayMinutes > 59) {
    throw new IllegalArgumentException("Delay in minutes should be between 0 and 59 (inclusive)");
  }

  // Setup window
  Calendar windowStartTime = Calendar.getInstance();
  windowStartTime.set(Calendar.HOUR_OF_DAY, windowStartHour);
  windowStartTime.set(Calendar.MINUTE, 0);
  windowStartTime.set(Calendar.SECOND, 0);

  Calendar windowEndTime = Calendar.getInstance();
  windowEndTime.set(Calendar.HOUR_OF_DAY, windowEndHour);
  windowEndTime.set(Calendar.MINUTE, 0);
  windowEndTime.set(Calendar.SECOND, 0);

  // Check if current time is between windowStartTime and windowEndTime, then let the execution happen
  // after delayMinutes minutes
  Calendar now = Calendar.getInstance();
  if (now.after(windowStartTime) && now.before(windowEndTime)) {
    // Azkaban takes a few seconds / a minute to bootstrap,
    // so extra few minutes get the first execution to run instantly
    now.add(Calendar.MINUTE, delayMinutes);

    return new SimpleDateFormat("hh,mm,a,z").format(now.getTime());
  }

  // Current time is not between windowStartTime and windowEndTime, so get random execution time for next day
  int allowedSchedulingWindow = (int)((windowEndTime.getTimeInMillis() - windowStartTime.getTimeInMillis()) /
      MILLISECONDS_IN_HOUR);
  int randomHourInWindow = new Random(System.currentTimeMillis()).nextInt(allowedSchedulingWindow);
  int randomMinute = new Random(System.currentTimeMillis()).nextInt(60);
  windowStartTime.add(Calendar.HOUR, randomHourInWindow);
  windowStartTime.set(Calendar.MINUTE, randomMinute);

  return new SimpleDateFormat("hh,mm,a,z").format(windowStartTime.getTime());
}
 
Example 19
Source File: TimeUtil.java    From UltimateCore with MIT License 4 votes vote down vote up
public static String formatDateDiff(Calendar fromDate, Calendar toDate, int maxacc, @Nullable Integer disable) {
    boolean future = false;
    if (toDate.equals(fromDate)) {
        return Messages.getColored("core.time.now");
    }
    if (toDate.after(fromDate)) {
        future = true;
    }
    StringBuilder sb = new StringBuilder();
    int[] types = {1, 2, 5, 11, 12, 13};

    String[] names = {
            Messages.getColored("core.time.years"),
            Messages.getColored("core.time.year"),
            Messages.getColored("core.time.months"),
            Messages.getColored("core.time.month"),
            Messages.getColored("core.time.days"),
            Messages.getColored("core.time.day"),
            Messages.getColored("core.time.hours"),
            Messages.getColored("core.time.hour"),
            Messages.getColored("core.time.minutes"),
            Messages.getColored("core.time.minute"),
            Messages.getColored("core.time.seconds"),
            Messages.getColored("core.time.second")
    };

    int accuracy = 0;
    for (int i = 0; i < types.length; i++) {
        if (accuracy >= maxacc) {
            break;
        }
        int diff = dateDiff(types[i], fromDate, toDate, future);
        if (diff > 0) {
            accuracy++;
            int name = ((i * 2) + (diff == 1 ? 1 : 0));
            if (disable != null && name >= disable) {
                continue;
            }
            sb.append(" ").append(diff).append(" ").append(names[name]);
        }
    }
    if (sb.length() == 0) {
        return Messages.getColored("core.time.now");
    }
    return sb.toString().trim();
}
 
Example 20
Source File: Walkin_CheckinWindow.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 4 votes vote down vote up
private PropertyChangeListener chechkDates() {
	final PropertyChangeListener listener = new PropertyChangeListener() {

		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			
			// here leave ancestors empty because we need dates not ancestor
			if (evt.getPropertyName().equals("ancestor")) {
				return;
			}
			
			boolean showed = false;
			startDate = checkinDateChooser.getDate();
			endDate = checkoutDateChooser.getDate();

			if (startDate != null && endDate != null) {
				// add to calendar to be able get day of date
				// and compare
				Calendar cs = Calendar.getInstance();
				cs.setTime(startDate);
				Calendar ce = Calendar.getInstance();
				ce.setTime(endDate);

				// compare if start date greater than end date
				if (cs.after(ce) && !showed) {
					JOptionPane.showMessageDialog(null, "Start date is after end date!",
							JOptionPane.MESSAGE_PROPERTY, JOptionPane.WARNING_MESSAGE);
					showed = true;
				}
				// or both is same date
				else if (cs.get(Calendar.DAY_OF_YEAR) == ce.get(Calendar.DAY_OF_YEAR) && !showed) {
					JOptionPane.showMessageDialog(null,
							"Start date equals end date!\nPlease be sure you're choose right date.",
							JOptionPane.MESSAGE_PROPERTY, JOptionPane.WARNING_MESSAGE);
					showed = true;
				}
				// other odds
				else {
					value = (int) ((startDate.getTime() - endDate.getTime()) / (1000 * 60 * 60 * 24));
					totalDaysField.setText(Math.abs(value) + "");
					totalDaysField.revalidate();
					totalDaysField.repaint();
				}

			}
		}
	};
	return listener;
}