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

The following examples show how to use java.util.Calendar#before() . 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: CostCalculatorPerUnit.java    From development with Apache License 2.0 6 votes vote down vote up
private Calendar determineStartTimeForFactorCalculation(
        PricingPeriod pricingPeriod, Calendar chargedPeriodStart,
        long usagePeriodStart, boolean adjustUsagePeriodStart) {
    Calendar startTime;
    if (adjustUsagePeriodStart) {
        startTime = PricingPeriodDateConverter.getStartTime(
                usagePeriodStart, pricingPeriod);
    } else {
        startTime = Calendar.getInstance();
        startTime.setTimeInMillis(usagePeriodStart);
    }

    if (startTime.before(chargedPeriodStart)) {
        return chargedPeriodStart;
    } else {
        return startTime;
    }
}
 
Example 2
Source File: CalendarIMMDateCalculator.java    From objectlabkit with Apache License 2.0 6 votes vote down vote up
@Override
protected Calendar getNextIMMDate(final boolean requestNextIMM, final Calendar startDate, final IMMPeriod period) {

    Calendar cal = (Calendar) startDate.clone();

    if (isIMMMonth(cal)) {
        moveToIMMDay(cal);
        if (requestNextIMM && cal.after(startDate) || !requestNextIMM && cal.before(startDate)) {
            return cal;
        }
    }

    final int delta = requestNextIMM ? 1 : -1;
    do {
        cal.add(MONTH, delta);
    } while (!isIMMMonth(cal));

    moveToIMMDay(cal);

    cal = handlePeriod(requestNextIMM, period, cal);

    return cal;
}
 
Example 3
Source File: LoadNotesListTask.java    From nextcloud-notes with GNU General Public License v3.0 6 votes vote down vote up
private String getTimeslot(DBNote note) {
    if (note.isFavorite()) {
        return "";
    }
    Calendar modified = note.getModified();
    for (Timeslot timeslot : timeslots) {
        if (!modified.before(timeslot.time)) {
            return timeslot.label;
        }
    }
    if (!modified.before(this.lastYear)) {
        // use YEAR and MONTH in a format based on current locale
        return DateUtils.formatDateTime(context, modified.getTimeInMillis(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_NO_MONTH_DAY);
    } else {
        return Integer.toString(modified.get(Calendar.YEAR));
    }
}
 
Example 4
Source File: PerDiemMaintenanceDocumentPresentationController.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 *
 * @see org.kuali.rice.kns.document.authorization.MaintenanceDocumentPresentationControllerBase#canMaintain(java.lang.Object)
 */
@Override
public boolean canMaintain(Object dataObject) {
    if (dataObject instanceof PerDiem) {
        final PerDiem perDiem = (PerDiem)dataObject;
        if (perDiem.getEffectiveToDate() != null) {
            Calendar now = Calendar.getInstance();
            now.setTimeInMillis(KfsDateUtils.clearTimeFields(getDateTimeService().getCurrentDate()).getTime());
            Calendar perDiemEndDate = Calendar.getInstance();
            perDiemEndDate.setTimeInMillis(KfsDateUtils.clearTimeFields(perDiem.getEffectiveToDate()).getTime());
            if (perDiemEndDate.before(now)) {
                return false;
            }
        }
    }
    return super.canMaintain(dataObject);
}
 
Example 5
Source File: SimpleAcceptanceTest.java    From junit-dataprovider with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@UseDataProvider("dataProviderWithNonConstantObjects")
void testWithNonConstantObjects(Calendar cal1, Calendar cal2, boolean cal1IsEarlierThenCal2) {
    // Given:

    // When:
    boolean result = cal1.before(cal2);

    // Then:
    assertThat(result).isEqualTo(cal1IsEarlierThenCal2);
}
 
Example 6
Source File: SAMLTokenValidator.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static boolean hasExpired(Element assertion) {
   if (assertion != null && STSHelper.getConditions(assertion).getLength() > 0) {
      Calendar calNotOnOrAfter = Calendar.getInstance();
      calNotOnOrAfter.setTime(STSHelper.getNotOnOrAfterConditions(assertion).getTime());
      Calendar now = Calendar.getInstance();
      return !now.before(calNotOnOrAfter);
   } else {
      return true;
   }
}
 
Example 7
Source File: DateUtilsBasic.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 检查 curDate 是否在 startDate 前1天之后,endDate 后1天之前.
 * @param startDate
 *            	开始日期字符串,以 yyyy-MM-dd 格式
 * @param endDate
 *            	结束日期字符串,以 yyyy-MM-dd 格式
 * @param curDate
 *            	要判断的日期字符串,以 yyyy-MM-dd 格式
 * @return boolean
 * 				如果 curDate 在 startDate 前1天之后,在 endDate 后1天之前,返回true;否则返回 false.
 */
public static boolean isBetween(String startDate, String endDate, String curDate) {
	Calendar startCalendar = Calendar.getInstance();
	startCalendar.setTime(strToDate(startDate));
	startCalendar.add(Calendar.DAY_OF_YEAR, -1);
	Calendar endCalendar = Calendar.getInstance();
	endCalendar.setTime(strToDate(endDate));
	endCalendar.add(Calendar.DAY_OF_YEAR, 1);
	Calendar curCalendar = Calendar.getInstance();
	curCalendar.setTime(strToDate(curDate));
	if (startCalendar.before(curCalendar) && curCalendar.before(endCalendar)) {
		return true;
	}
	return false;
}
 
Example 8
Source File: DateTimeUtils.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the next Calendar from today.
 */
public static Calendar getNext(Calendar... calendars) {
    Calendar now = Calendar.getInstance();
    Calendar next = null;
    for (Calendar calendar : calendars) {
        if (calendar.after(now) && (next == null || calendar.before(next))) {
            next = calendar;
        }
    }
    return next;
}
 
Example 9
Source File: Dates.java    From howsun-javaee-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 求真实年龄
 * @param birthDay
 * @return
 * @throws Exception
 */
public static int getAge(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);
       int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
       cal.setTime(birthDay);

       int yearBirth = cal.get(Calendar.YEAR);
       int monthBirth = cal.get(Calendar.MONTH);
       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 {
                   //do nothing
               }
           } else {
               //monthNow>monthBirth
               age--;
           }
       } else {
           //monthNow<monthBirth
           //donothing
       }

       return age;
   }
 
Example 10
Source File: DateUtilsBasic.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 根据出生日期计算年龄.
 * @param birthDay
 *            出生日期
 * @return int
 * 			  年龄.
 * @throws Exception
 *            如果出生日期在当前日期之后,抛出异常
 */
public static int getAge(Date birthDay) throws Exception {
	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);
	int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
	cal.setTime(birthDay);

	int yearBirth = cal.get(Calendar.YEAR);
	int monthBirth = cal.get(Calendar.MONTH);
	int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

	int age = yearNow - yearBirth;
	if (monthNow <= monthBirth) {
		if (monthNow == monthBirth) {
			if (dayOfMonthNow < dayOfMonthBirth) {
				age--;
			} 
		} else {
			age--;
		}
	} 
	return age;
}
 
Example 11
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 astronomical 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 astronomical twilight at the given location and the given calendar.
 * This returns true if the given time at the location is between nautical and astronomical twilight dusk
 * or between astronomical and nautical twilight dawn.
 */
public static boolean isAstronomicalTwilight(Calendar calendar, double latitude, double longitude) {
    Calendar[] nauticalTwilight = getNauticalTwilight(calendar, latitude, longitude);
    if (nauticalTwilight == null) return false;
    Calendar[] astronomicalTwilight = getAstronomicalTwilight(calendar, latitude, longitude);
    if (astronomicalTwilight == null) return false;

    return (calendar.after(nauticalTwilight[1]) && calendar.before(astronomicalTwilight[1])
            || (calendar.after(astronomicalTwilight[0]) && calendar.before(nauticalTwilight[0])));
}
 
Example 12
Source File: DateTimeHelper.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * 根据生日去用户年龄
 * 
 * @param birthday
 * @return int
 * @exception @Date
 *                Apr 24, 2008
 */
public static int getUserAge(Date birthday) {

    if (birthday == null)
        return 0;
    Calendar cal = Calendar.getInstance();
    if (cal.before(birthday)) {
        return 0;
    }
    int yearNow = cal.get(Calendar.YEAR);
    cal.setTime(birthday);// 给时间赋值
    int yearBirth = cal.get(Calendar.YEAR);
    return yearNow - yearBirth;
}
 
Example 13
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 14
Source File: DateUtil.java    From software-demo with MIT License 5 votes vote down vote up
public static int getAgeByBirth(Date birthday) {

		//Calendar:日历
		/*从Calendar对象中或得一个Date对象*/
		Calendar cal = Calendar.getInstance();
		/*把出生日期放入Calendar类型的bir对象中,进行Calendar和Date类型进行转换*/
		Calendar bir = Calendar.getInstance();
		bir.setTime(birthday);
		/*如果生日大于当前日期,则抛出异常:出生日期不能大于当前日期*/
		if(cal.before(bir)){
			throw new IllegalArgumentException("The birthday is before Now,It's unbelievable");
		}
		/*取出当前年月日*/
		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH);
		int dayNow = cal.get(Calendar.DAY_OF_MONTH);
		/*取出出生年月日*/
		int yearBirth = bir.get(Calendar.YEAR);
		int monthBirth = bir.get(Calendar.MONTH);
		int dayBirth = bir.get(Calendar.DAY_OF_MONTH);
		/*大概年龄是当前年减去出生年*/
		int age = yearNow - yearBirth;
		/*如果出当前月小与出生月,或者当前月等于出生月但是当前日小于出生日,那么年龄age就减一岁*/
		if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
			age--;
		}
		return age;
	}
 
Example 15
Source File: DateUtils.java    From cms with Apache License 2.0 5 votes vote down vote up
/**
 * @author jerry.chen
 * @param brithday
 * @return
 * @throws ParseException
 *             根据生日获取年龄;
 */
public static int getCurrentAgeByBirthDate(Date birtnDay) {
	Calendar cal = Calendar.getInstance();

	if (cal.before(birtnDay)) {
		return 0;
	}

	int yearNow = cal.get(Calendar.YEAR);
	int monthNow = cal.get(Calendar.MONTH);
	int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
	cal.setTime(birtnDay);

	int yearBirth = cal.get(Calendar.YEAR);
	int monthBirth = cal.get(Calendar.MONTH);
	int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

	int age = yearNow - yearBirth;

	if (monthNow <= monthBirth) {
		if (monthNow == monthBirth) {
			if (dayOfMonthNow < dayOfMonthBirth) {
				age--;
			}
		} else {
			age--;
		}
	}

	return age;
}
 
Example 16
Source File: PriorYearAccount.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This method determines whether the account is expired or not. Note that if Expiration Date is the same date as testDate, then
 * this will return false. It will only return true if the account expiration date is one day earlier than testDate or earlier.
 * Note that this logic ignores all time components when doing the comparison. It only does the before/after comparison based on
 * date values, not time-values.
 *
 * @param testDate - Calendar instance with the date to test the Account's Expiration Date against. This is most commonly set to
 *        today's date.
 * @return true or false based on the logic outlined above
 */
@Override
public boolean isExpired(Calendar testDate) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("entering isExpired(" + testDate + ")");
    }

    // dont even bother trying to test if the accountExpirationDate is null
    if (this.accountExpirationDate == null) {
        return false;
    }

    // remove any time-components from the testDate
    testDate = DateUtils.truncate(testDate, Calendar.DAY_OF_MONTH);

    // get a calendar reference to the Account Expiration
    // date, and remove any time components
    Calendar acctDate = Calendar.getInstance();
    acctDate.setTime(this.accountExpirationDate);
    acctDate = DateUtils.truncate(acctDate, Calendar.DAY_OF_MONTH);

    // if the Account Expiration Date is before the testDate
    if (acctDate.before(testDate)) {
        return true;
    }
    else {
        return false;
    }
}
 
Example 17
Source File: ServerMain.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws IOException {
    System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");
    System.setProperty("org.slf4j.simpleLogger.log.nifi.io.nio", "debug");

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
    final Map<StreamConsumer, ScheduledFuture<?>> consumerMap = new ConcurrentHashMap<>();
    final BufferPool bufferPool = new BufferPool(10, 5 << 20, false, 40.0);
    ChannelListener listener = null;
    try {
        executor.scheduleWithFixedDelay(bufferPool, 0L, 5L, TimeUnit.SECONDS);
        listener = new ChannelListener(5, new ExampleStreamConsumerFactory(executor, consumerMap), bufferPool, 5, TimeUnit.MILLISECONDS, false);
        listener.setChannelReaderSchedulingPeriod(50L, TimeUnit.MILLISECONDS);
        listener.addDatagramChannel(null, 20000, 32 << 20);
        LOGGER.info("Listening for UDP data on port 20000");
        listener.addServerSocket(null, 20001, 64 << 20);
        LOGGER.info("listening for TCP connections on port 20001");
        listener.addServerSocket(null, 20002, 64 << 20);
        LOGGER.info("listening for TCP connections on port 20002");
        final Calendar endTime = Calendar.getInstance();
        endTime.add(Calendar.MINUTE, 30);
        while (true) {
            processAllConsumers(consumerMap);
            if (endTime.before(Calendar.getInstance())) {
                break; // time to shut down
            }
        }
    } finally {
        if (listener != null) {
            LOGGER.info("Shutting down server....");
            listener.shutdown(1L, TimeUnit.SECONDS);
            LOGGER.info("Consumer map size = " + consumerMap.size());
            while (consumerMap.size() > 0) {
                processAllConsumers(consumerMap);
            }
            LOGGER.info("Consumer map size = " + consumerMap.size());
        }
        executor.shutdown();
    }
}
 
Example 18
Source File: NominatimLocationService.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
private boolean recordDateIsNotValidOrIsTooOld(long recordCreatedinMilis) {
    Calendar now = Calendar.getInstance();
    Calendar calendarRecordCreated = Calendar.getInstance();
    calendarRecordCreated.setTimeInMillis(recordCreatedinMilis);

    int timeToLiveRecordsInCacheInHours = 8760;/*Integer.parseInt(
            PreferenceManager.getDefaultSharedPreferences(this).getString(SettingsActivity.LOCATION_CACHE_LASTING_HOURS, "720"))*/;

    calendarRecordCreated.add(Calendar.HOUR_OF_DAY, timeToLiveRecordsInCacheInHours);
    return calendarRecordCreated.before(now);
}
 
Example 19
Source File: RegistryMatchingManager.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
public List<Subscription> getMatchingSubscriptions(String topicName)
        throws EventBrokerException {

    // since all the subscriptions for the same topic is stored in the
    // same path we can get all the subscriptions by getting all the chlid
    // resources under to topoic name.

    String topicResourcePath =  JavaUtil.getResourcePath(topicName, this.subscriptionStoragePath);

    if (!topicResourcePath.endsWith("/")) {
        topicResourcePath += "/";
    }

    topicResourcePath += EventBrokerConstants.EB_CONF_WS_SUBSCRIPTION_COLLECTION_NAME;
    List<Subscription> matchingSubscriptions = new ArrayList();

    try {
        UserRegistry userRegistry =
                this.registryService.getGovernanceSystemRegistry(EventBrokerHolder.getInstance().getTenantId());
        String subscriptionID = null;
        if (userRegistry.resourceExists(topicResourcePath)) {
            Collection subscriptions = (Collection) userRegistry.get(topicResourcePath);
            String[] subscriptionPaths = (String[]) subscriptions.getContent();
            for (String subscriptionPath : subscriptionPaths) {
                Resource resource = userRegistry.get(subscriptionPath);
                Subscription subscription = JavaUtil.getSubscription(resource);
                subscriptionID = subscriptionPath.substring(subscriptionPath.lastIndexOf("/") + 1);
                subscription.setId(subscriptionID);
                subscription.setTopicName(topicName);

                // check for expiration
                Calendar current = Calendar.getInstance(); //Get current date and time
                if (subscription.getExpires() != null) {
                    if (current.before(subscription.getExpires())) {
                        // add only valid subscriptions by checking the expiration
                        matchingSubscriptions.add(subscription);
                    }
                } else {
                    // If a expiration dosen't exisits treat it as a never expire subscription, valid till unsubscribe
                    matchingSubscriptions.add(subscription);
                }
            }
        }
    } catch (RegistryException e) {
        throw new EventBrokerException("Can not get the Registry ", e);
    }

    return matchingSubscriptions;
}
 
Example 20
Source File: TravelDocumentServiceImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Integer calculatePerDiemPercentageFromTimestamp(PerDiemExpense perDiemExpense, Timestamp tripEnd) {
    if (perDiemExpense.getMileageDate() != null) {
        try {
            Collection<String> quarterTimes = parameterService.getParameterValuesAsString(TemParameterConstants.TEM_DOCUMENT.class, TravelParameters.QUARTER_DAY_TIME_TABLE);

            // Take date and compare to the quadrant specified.
            Calendar prorateDate = new GregorianCalendar();
            prorateDate.setTime(perDiemExpense.getMileageDate());

            int quadrantIndex = 4;
            for (String qT : quarterTimes) {
                String[] indexTime = qT.split("=");
                String[] hourMinute = indexTime[1].split(":");

                Calendar qtCal = new GregorianCalendar();
                qtCal.setTime(perDiemExpense.getMileageDate());
                qtCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourMinute[0]));
                qtCal.set(Calendar.MINUTE, Integer.parseInt(hourMinute[1]));

                if (prorateDate.equals(qtCal) || prorateDate.before(qtCal)) {
                    quadrantIndex = Integer.parseInt(indexTime[0]);
                    break;
                }
            }

            // Prorate on trip begin. (12:01 AM arrival = 100%, 11:59 PM arrival = 25%)
            if (tripEnd != null && !KfsDateUtils.isSameDay(prorateDate.getTime(), tripEnd)) {
                return 100 - ((quadrantIndex - 1) * TemConstants.QUADRANT_PERCENT_VALUE);
            }
            else { // Prorate on trip end. (12:01 AM departure = 25%, 11:59 PM arrival = 100%).
                return quadrantIndex * TemConstants.QUADRANT_PERCENT_VALUE;
            }
        }
        catch (IllegalArgumentException e2) {
            LOG.error("IllegalArgumentException.", e2);
        }
    }

    return 100;
}