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

The following examples show how to use java.util.Date#after() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: live-chat-engine   File: TariffMath.java    License: Apache License 2.0 6 votes vote down vote up
public static BigDecimal calcForPeriod(BigDecimal monthPrice, 
		Date begin, 
		Date end,
		BigDecimal minVal) {
	
	if(monthPrice == null) 
		throw new IllegalArgumentException("monthPrice must be not null");
	if(begin.after(end)) 
		throw new IllegalArgumentException("begin must be before end: "+begin+", "+end);
	
	
	BigDecimal secPrice = divideForSecPrice(monthPrice);
	long secCount = (end.getTime() - begin.getTime()) / 1000;
	BigDecimal result = secPrice.multiply(new BigDecimal(secCount));
	result = round(result);
	
	if(result.compareTo(minVal) < 0){
		result = round(minVal);
	}
	
	return result;
}
 
Example 2
@Override
public boolean isDay(Calendar dateTime)
{
    Calendar sunsetCal = getOfficialSunriseCalendarForDate(dateTime);
    if (sunsetCal == null)    // no sunset time, must be day
        return true;

    Calendar sunriseCal = getOfficialSunsetCalendarForDate(dateTime);
    if (sunriseCal == null)   // no sunrise time, must be night
        return false;

    Date time = dateTime.getTime();
    Date sunrise = sunriseCal.getTime();
    Date sunset = sunsetCal.getTime();
    return (time.after(sunrise) && time.before(sunset));
}
 
Example 3
public boolean isDay(Calendar dateTime)
{
    if (dataActual.calculator == null)
    {
        Calendar sunsetCal = dataActual.sunsetCalendarToday();
        if (sunsetCal == null)    // no sunset time, must be day
            return true;

        Calendar sunriseCal = dataActual.sunriseCalendarToday();
        if (sunriseCal == null)   // no sunrise time, must be night
            return false;

        Date time = dateTime.getTime();
        Date sunrise = sunriseCal.getTime();
        Date sunset = sunsetCal.getTime();
        return (time.after(sunrise) && time.before(sunset));

    } else {
        return dataActual.isDay(dateTime);
    }
}
 
Example 4
Source Project: AsuraFramework   File: DateCalculator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 计算两个时间段间隔里面按照固定间隔返回时间点集合
 * <p/>
 * 这里会 startDate 到 endDate 最后endDate如果相等会算入集合
 * 如:[2016-10-20 12:00:00.000 -2016-10-20 13:00:00.000,'yyyy-MM-dd HH:mm',30]
 * 返回:["2016-10-20 12:00","2016-10-20 12:30","2016-10-20 13:00"]
 * @param date1
 * @param date2
 * @param minutesSplit 间隔多少分
 * @param pattern
 * @return
 */
public static List<String> getTimePointBetweenDates(@NotNull Date date1, @NotNull Date date2, @NotNull String pattern, int minutesSplit) {
    Objects.requireNonNull(date1, "startDate must not null");
    Objects.requireNonNull(date2, "endDate must not null");
    Objects.requireNonNull(pattern, "pattern must not null");
    Date startDate = date1;
    Date endDate = date2;
    //调整顺序
    if (date1.after(date2)) {
        startDate = date2;
        endDate = date1;
    }
    DateTime startDateTime = new DateTime(startDate);
    DateTime endDateTime = new DateTime(endDate);
    List<String> points = new ArrayList<>();
    while (startDateTime.isBefore(endDateTime.getMillis()) || startDateTime.getMillis() == endDateTime.getMillis()) {
        points.add(DateFormatter.format(startDateTime.getMillis(), pattern));
        startDateTime = startDateTime.plusMinutes(minutesSplit);
    }
    return points;
}
 
Example 5
public int compare(Object o1, Object o2) {
	// TODO Auto-generated method stub
	long score1 = ((TeamRankObj) o1).getScore();
	long score2 = ((TeamRankObj) o2).getScore();
	Date submit1 = ((TeamRankObj) o1).getLastSummit();
	Date submit2 = ((TeamRankObj) o2).getLastSummit();
	if (score1>score2) {
		return -1;
	} else {
		if (score1<score2) {
			return 1;
		} else {
			if (submit1.before(submit2)) {
				return -1;
			} else {
				if (submit1.after(submit2)) {
					return 1;
				} else {
					return 0;
				}
			}
		}
	}
}
 
Example 6
/**
 * 计算两个Date之间的工作日时间差
 *
 * @param start 开始时间
 * @param end   结束时间
 * @return int 返回两天之间的工作日时间
 */
public static int countDutyday(Date start, Date end) {
    if (start == null || end == null) return 0;
    if (start.after(end)) return 0;
    Calendar c_start = Calendar.getInstance();
    Calendar c_end = Calendar.getInstance();
    c_start.setTime(start);
    c_end.setTime(end);
    //时分秒毫秒清零
    c_start.set(Calendar.HOUR_OF_DAY, 0);
    c_start.set(Calendar.MINUTE, 0);
    c_start.set(Calendar.SECOND, 0);
    c_start.set(Calendar.MILLISECOND, 0);
    c_end.set(Calendar.HOUR_OF_DAY, 0);
    c_end.set(Calendar.MINUTE, 0);
    c_end.set(Calendar.SECOND, 0);
    c_end.set(Calendar.MILLISECOND, 0);
    //初始化第二个日期,这里的天数可以随便的设置
    int dutyDay = 0;
    while (c_start.compareTo(c_end) < 0) {
        if (c_start.get(Calendar.DAY_OF_WEEK) != 1 && c_start.get(Calendar.DAY_OF_WEEK) != 7)
            dutyDay++;
        c_start.add(Calendar.DAY_OF_YEAR, 1);
    }
    return dutyDay;
}
 
Example 7
public static Date getSmaller(Date first, Date second) {
    if ((first == null) && (second == null)) {
        return null;
    }

    if (first == null) {
        return second;
    }

    if (second == null) {
        return first;
    }

    if (first.before(second)) {
        return first;
    }

    if (first.after(second)) {
        return second;
    }

    return first;
}
 
Example 8
Source Project: htmlunit   File: CookieManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Clears all cookies that have expired before supplied date.
 * If disabled, this returns false.
 * @param date the date to use for comparison when clearing expired cookies
 * @return whether any cookies were found expired, and were cleared
 */
public synchronized boolean clearExpired(final Date date) {
    if (!isCookiesEnabled()) {
        return false;
    }

    if (date == null) {
        return false;
    }

    boolean foundExpired = false;
    for (final Iterator<Cookie> iter = cookies_.iterator(); iter.hasNext();) {
        final Cookie cookie = iter.next();
        if (cookie.getExpires() != null && date.after(cookie.getExpires())) {
            iter.remove();
            foundExpired = true;
        }
    }
    return foundExpired;
}
 
Example 9
Source Project: iMoney   File: TimeUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 判断钥匙是否在有效期内
 *
 * @param Auth_start_date
 * @param Auth_end_date
 * @return
 */
public static boolean isInValid(String Auth_start_date, String Auth_end_date) {
    try {
        Date now = new Date();
        Date end_date = sdf.parse(Auth_end_date);
        Date start_date = sdf.parse(Auth_start_date);
        Log.i(TAG, "卡片授权时间:start=" + start_date + ",end=" + end_date);
        return now.before(end_date) && now.after(start_date);
    } catch (ParseException e) {
        e.printStackTrace();
        Log.i(TAG, "解析授权时间失败");
    }
    return false;
}
 
Example 10
boolean isDateAfterReleaseDate(long witnessDateAsLong, Date ageWitnessReleaseDate, ErrorMessageHandler errorMessageHandler) {
    // Release date minus 1 day as tolerance for not synced clocks
    Date releaseDateWithTolerance = new Date(ageWitnessReleaseDate.getTime() - TimeUnit.DAYS.toMillis(1));
    final Date witnessDate = new Date(witnessDateAsLong);
    final boolean result = witnessDate.after(releaseDateWithTolerance);
    if (!result) {
        final String msg = "Witness date is set earlier than release date of ageWitness feature. " +
                "ageWitnessReleaseDate=" + ageWitnessReleaseDate + ", witnessDate=" + witnessDate;
        log.warn(msg);
        errorMessageHandler.handleErrorMessage(msg);
    }
    return result;
}
 
Example 11
/**
 * Assert that the date <code>later</code> is after the date
 * <code>earlier</code>. The assertion succeeds if the dates
 * are equal. Both dates must be non-null.
 *
 * @param msg the message to print if the assertion fails
 * @param earlier the earlier date to compare
 * @param later the later date to compare
 */
public static void assertNotBefore(String msg, Date earlier, Date later) {
    assertNotNull(msg, earlier);
    assertNotNull(msg, later);
    if (earlier.after(later) && !earlier.equals(later)) {
        String e = DateFormat.getDateTimeInstance().format(earlier);
        String l = DateFormat.getDateTimeInstance().format(later);
        throw new ComparisonFailure(msg, e, l);
    }
}
 
Example 12
/**
 * Whether this lock has expired. If no expiry is set (i.e. expires is null)
 * then false is always returned.
 * 
 * @return true if expired.
 */
@Override
@JsonIgnore
public boolean isExpired()
{
    if (expires == null)
    {
        return false;
    }
    Date now = dateNow();
    return now.after(expires);
}
 
Example 13
/**
 * Checks if the given {@code timeCoding} is within the start and end time of this {@link TimeCoding}.
 *
 * @param timeCoding the time coding to check if it is within this {@code TimeCoding}
 *
 * @return whether this {@code TimeCoding} contains the given time coding
 */
public boolean contains(TimeCoding timeCoding) {
    Date thisStartDate = getStartTime().getAsDate();
    Date thisEndDate = getEndTime().getAsDate();
    Date otherStartDate = timeCoding.getStartTime().getAsDate();
    Date otherEndDate = timeCoding.getEndTime().getAsDate();
    return !thisStartDate.after(otherStartDate) && !thisEndDate.before(otherEndDate);
}
 
Example 14
private Date updateLast(Date lastUpdate, Date thisUpdate) {
	if (lastUpdate == null) { //First
		lastUpdate = thisUpdate;
	} else if (thisUpdate.after(lastUpdate)) {
		lastUpdate = thisUpdate;
	}
	return lastUpdate;
}
 
Example 15
private boolean isThereValidContentTimestampAfterDate(SignatureWrapper currentSignature, Date date) {
	List<TimestampWrapper> contentTimestamps = currentSignature.getContentTimestamps();
	if (Utils.isCollectionNotEmpty(contentTimestamps)) {
		for (TimestampWrapper timestamp : contentTimestamps) {
			if (isValidTimestamp(timestamp)) {
				Date tspProductionTime = timestamp.getProductionTime();
				if (tspProductionTime.after(date)) {
					return true;
				}
			}
		}
	}
	return false;
}
 
Example 16
private boolean after(final Object object1, final Object object2) {
	Date date1 = getDate(object1, false);
	Date date2 = getDate(object2, true);
	if (date1 != null && date2 != null) {
		CALENDAR.setTime(date2);
		CALENDAR.set(Calendar.HOUR_OF_DAY, 23);
		CALENDAR.set(Calendar.MINUTE, 59);
		CALENDAR.set(Calendar.SECOND, 59);
		CALENDAR.set(Calendar.MILLISECOND, 999);
		return date1.after(CALENDAR.getTime());
	}
	return false;
}
 
Example 17
Source Project: convalida   File: PastDateValidator.java    License: Apache License 2.0 4 votes vote down vote up
private boolean afterOrEqualsTo(Date current, Date limit) {
    return current.equals(limit) || current.after(limit);
}
 
Example 18
@Override
protected boolean validateFormLogic(final UserRequest ureq) {
    boolean retVal = true;
    // (1)
    // dateswitch is enabled and the datefields are valid
    // check complex rules involving checks over multiple elements
    final Date fromDateVal = fromDate.getDate();
    final Date toDateVal = toDate.getDate();
    if (dateSwitch.getSelectedKeys().size() == 1 && !fromDate.hasError() && !toDate.hasError()) {
        // one must be set
        if (fromDate.isEmpty() && toDate.isEmpty()) {
            // error concern both input fields -> set it as switch error
            dateSubContainer.setErrorKey("form.easy.error.date");
            retVal = false;
        } else {
            // remove general error
            dateSubContainer.clearError();
        }
        // check valid dates

        // if both are set, check from < to
        if (fromDateVal != null && toDateVal != null) {
            /*
             * bugfix http://bugs.olat.org/jira/browse/OLAT-813 valid dates and not empty, in easy mode we assume that Start and End date should implement the meaning
             * of ----false---|S|-----|now|-TRUE---------|E|---false--->t ............. Thus we check for Startdate < Enddate, error otherwise
             */
            if (fromDateVal.after(toDateVal)) {
                dateSubContainer.setErrorKey("form.easy.error.bdateafteredate");
                retVal = false;
            } else {
                // remove general error
                dateSwitch.clearError();
            }
        } else {
            if (fromDateVal == null && !fromDate.isEmpty()) {
                // not a correct begin date
                fromDate.setErrorKey("form.easy.error.bdate", null);
                retVal = false;
            }
            if (toDateVal == null && !toDate.isEmpty()) {
                toDate.setErrorKey("form.easy.error.edate", null);
                retVal = false;
            }
        }
    }

    // (2)
    // groups switch is enabled
    // check if either group or area is defined
    retVal = validateGroupFields() && retVal;

    if (assessmentSwitch.getSelectedKeys().size() == 1) {
        // foop d fbg,dfbg,f ,gfbirst check two error cases of a selection
        // no node selected or a deleted node selected
        if (nodePassed.getSelectedKey().equals(NO_NODE_SELECTED_IDENTIFYER)) {
            assessNodesListContainer.setErrorKey("form.easy.error.nodePassed", null);
            retVal = false;
        } else if (nodePassed.getSelectedKey().equals(DELETED_NODE_IDENTIFYER)) {
            assessNodesListContainer.setErrorKey("form.easy.error.nodeDeleted", null);
            retVal = false;
        } else {
            // clear nodepassed error
            assessNodesListContainer.clearError();
            // retVal stays
        }
    }

    if (ShibbolethModule.isEnableShibbolethLogins()) {
        retVal = validateAttibuteFields() && retVal;
    }
    //
    return retVal;
}
 
Example 19
/**
 * @see org.kuali.kfs.module.ar.report.service.CustomerAgingReportService#calculateAgingReportAmounts()
 */
@Override
public CustomerAgingReportDataHolder calculateAgingReportAmounts(Collection<CustomerInvoiceDetail> details, Date reportRunDate) {
    CustomerAgingReportDataHolder agingData = new CustomerAgingReportDataHolder();

    KualiDecimal total0to30 = KualiDecimal.ZERO;
    KualiDecimal total31to60 = KualiDecimal.ZERO;
    KualiDecimal total61to90 = KualiDecimal.ZERO;
    KualiDecimal total91toSYSPR = KualiDecimal.ZERO;
    KualiDecimal totalSYSPRplus1orMore = KualiDecimal.ZERO;

    String nbrDaysForLastBucket = parameterService.getParameterValueAsString(CustomerAgingReportDetail.class, "CUSTOMER_INVOICE_AGE");     // ArConstants.CUSTOMER_INVOICE_AGE); // default is 120

    Date cutoffdate30 = DateUtils.addDays(reportRunDate, -30);
    Date cutoffdate60 = DateUtils.addDays(reportRunDate, -60);
    Date cutoffdate90 = DateUtils.addDays(reportRunDate, -90);
    Date cutoffdate120 = DateUtils.addDays(reportRunDate, -1*Integer.parseInt(nbrDaysForLastBucket));

    Map<String, Object> knownCustomers = new HashMap<String, Object>(details.size());
    Map<String, Object> retrievedInvoices = new HashMap<String, Object>(); // Simple caching mechanism to try to lower overhead for retrieving invoices that have multiple details

    KualiDecimal totalBalance = new KualiDecimal(0.00);
    CustomerAgingReportDetail custDetail = null;

    // iterate over all invoices consolidating balances for each customer
    for (CustomerInvoiceDetail cid : details) {
        String invoiceDocumentNumber = cid.getDocumentNumber();
        CustomerInvoiceDocument custInvoice;
        // check cache for already retrieved invoices before attempting to retrieve it from the DB
        if(retrievedInvoices.containsKey(invoiceDocumentNumber)) {
            custInvoice = (CustomerInvoiceDocument) retrievedInvoices.get(invoiceDocumentNumber);
        } else {
            custInvoice = customerInvoiceDocumentService.getInvoiceByInvoiceDocumentNumber(invoiceDocumentNumber);
            retrievedInvoices.put(invoiceDocumentNumber, custInvoice);
        }
        Date approvalDate=custInvoice.getBillingDate();
        if (ObjectUtils.isNull(approvalDate)) {
            continue;
        }

        // only for items that have positive amounts and non-zero open amounts - e.g. a discount should not be added
        if(ObjectUtils.isNotNull(custInvoice) && cid.getAmountOpen().isNonZero() && cid.getAmount().isPositive()) {
            Customer customerobj = custInvoice.getCustomer();
            String customerNumber = customerobj.getCustomerNumber();    // tested and works
            String customerName = customerobj.getCustomerName();  // tested and works

            if (knownCustomers.containsKey(customerNumber)) {
                custDetail = (CustomerAgingReportDetail) knownCustomers.get(customerNumber);
            } else {
                custDetail = new CustomerAgingReportDetail();
                custDetail.setCustomerName(customerName);
                custDetail.setCustomerNumber(customerNumber);
                knownCustomers.put(customerNumber, custDetail);
            }
            KualiDecimal amountOpenOnReportRunDate = cid.getAmountOpenByDateFromDatabase(reportRunDate);
            if (!approvalDate.after(reportRunDate) && !approvalDate.before(cutoffdate30)) {
                custDetail.setUnpaidBalance0to30(amountOpenOnReportRunDate.add(custDetail.getUnpaidBalance0to30()));
                total0to30 = total0to30.add(amountOpenOnReportRunDate);
            }
            else if (approvalDate.before(cutoffdate30) && !approvalDate.before(cutoffdate60)) {
                custDetail.setUnpaidBalance31to60(amountOpenOnReportRunDate.add(custDetail.getUnpaidBalance31to60()));
                total31to60 = total31to60.add(amountOpenOnReportRunDate);
            }
            else if (approvalDate.before(cutoffdate60) && !approvalDate.before(cutoffdate90)) {
                custDetail.setUnpaidBalance61to90(amountOpenOnReportRunDate.add(custDetail.getUnpaidBalance61to90()));
                total61to90 = total61to90.add(amountOpenOnReportRunDate);
            }
            else if (approvalDate.before(cutoffdate90) && !approvalDate.before(cutoffdate120)) {
                custDetail.setUnpaidBalance91toSYSPR(amountOpenOnReportRunDate.add(custDetail.getUnpaidBalance91toSYSPR()));
                total91toSYSPR = total91toSYSPR.add(amountOpenOnReportRunDate);
            }
            else if (approvalDate.before(cutoffdate120)) {
                custDetail.setUnpaidBalanceSYSPRplus1orMore(amountOpenOnReportRunDate.add(custDetail.getUnpaidBalanceSYSPRplus1orMore()));
                totalSYSPRplus1orMore = totalSYSPRplus1orMore.add(amountOpenOnReportRunDate);
            }
            totalBalance = totalBalance.add(amountOpenOnReportRunDate);
        }
    }

    agingData.setTotal0to30(total0to30);
    agingData.setTotal31to60(total31to60);
    agingData.setTotal61to90(total61to90);
    agingData.setTotal91toSYSPR(total91toSYSPR);
    agingData.setTotalSYSPRplus1orMore(totalSYSPRplus1orMore);
    agingData.setTotalAmountDue(totalBalance);

    agingData.setKnownCustomers(knownCustomers);

    return agingData;
}
 
Example 20
private boolean checkValidHours(Date beginning, Date end) {
    if (beginning.after(end)) {
        throw new DomainException("error.data.exame.invalida");
    }
    return true;
}