Example usage for org.apache.commons.lang3.time DateUtils MILLIS_PER_MINUTE

List of usage examples for org.apache.commons.lang3.time DateUtils MILLIS_PER_MINUTE

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateUtils MILLIS_PER_MINUTE.

Prototype

long MILLIS_PER_MINUTE

To view the source code for org.apache.commons.lang3.time DateUtils MILLIS_PER_MINUTE.

Click Source Link

Document

Number of milliseconds in a standard minute.

Usage

From source file:com.nridge.core.base.std.Sleep.java

public static void forMinutes(int aMinutes) {
    forMilliseconds(aMinutes * DateUtils.MILLIS_PER_MINUTE);
}

From source file:SampleLang.java

public static void checkDate() throws InterruptedException, ParseException {
    //date1 created
    Date date1 = new Date();
    //Print the date and time at this instant
    System.out.println("The time right now is >>" + date1);
    //Thread sleep for 1000 ms
    Thread.currentThread().sleep(DateUtils.MILLIS_PER_MINUTE);
    //date2 created.
    Date date2 = new Date();
    //Check if date1 and date2 have the same day
    System.out.println("Is Same Day >> " + DateUtils.isSameDay(date1, date2));
    //Check if date1 and date2 have the same instance
    System.out.println("Is Same Instant >> " + DateUtils.isSameInstant(date1, date2));
    //Round the hour
    System.out.println("Date after rounding >>" + DateUtils.round(date1, Calendar.HOUR));
    //Truncate the hour
    System.out.println("Date after truncation >>" + DateUtils.truncate(date1, Calendar.HOUR));
    //Three dates in three different formats
    String[] dates = { "2005.03.24 11:03:26", "2005-03-24 11:03", "2005/03/24" };
    //Iterate over dates and parse strings to java.util.Date objects
    for (int i = 0; i < dates.length; i++) {
        Date parsedDate = DateUtils.parseDate(dates[i],
                new String[] { "yyyy/MM/dd", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm" });
        System.out.println("Parsed Date is >>" + parsedDate);
    }/*www . ja  va2 s  . c o  m*/
    //Display date in HH:mm:ss format
    System.out.println("Now >>" + DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(System.currentTimeMillis()));
}

From source file:net.larry1123.util.api.time.StringTime.java

/**
 * Takes just a number or a set of numbers with a D, H, M or, S fallowing it
 * The letters can be upper or lower case
 * 15h 50m 5s// w w w .  j  av a2s. c o  m
 *
 * @param string Whole String to decode into parts
 *
 * @return the amount of time in milliseconds that the time string Decodes to
 */
public static long millisecondsFromString(String string) {
    if (string == null) {
        throw new NullPointerException("String can not be null");
    }
    string = string.trim();
    long ret = 0;
    try {
        ret = Long.parseLong(string);
    } catch (NumberFormatException e) {
        for (String part : string.split(" ")) {
            if (part.length() >= 2) {
                String time = part.substring(part.length() - 1);
                switch (Part.getFromString(time)) {
                case DAYS:
                    try {
                        Long days = Long.parseLong(part.substring(0, part.length() - 1));
                        ret += days * DateUtils.MILLIS_PER_DAY;
                    } catch (NumberFormatException error) {
                        // DO nothing right now
                    }
                    break;
                case HOUR:
                    try {
                        Long hours = Long.parseLong(part.substring(0, part.length() - 1));
                        ret += hours * DateUtils.MILLIS_PER_HOUR;
                    } catch (NumberFormatException error) {
                        // DO nothing right now
                    }
                    break;
                case MINUTES:
                    try {
                        Long minutes = Long.parseLong(part.substring(0, part.length() - 1));
                        ret += minutes * DateUtils.MILLIS_PER_MINUTE;
                    } catch (NumberFormatException error) {
                        // DO nothing right now
                    }
                    break;
                case SECONDS:
                    try {
                        Long seconds = Long.parseLong(part.substring(0, part.length() - 1));
                        ret += seconds * DateUtils.MILLIS_PER_SECOND;
                    } catch (NumberFormatException error) {
                        // DO nothing right now
                    }
                    break;
                default:
                    // Something is malformed just let it fly by and keep going
                    break;
                }
            } else if (part.length() == 1) {
                switch (Part.getFromString("" + part.charAt(1))) {
                case DAYS:
                    ret += DateUtils.MILLIS_PER_DAY;
                    break;
                case HOUR:
                    ret += DateUtils.MILLIS_PER_HOUR;
                    break;
                case MINUTES:
                    ret += DateUtils.MILLIS_PER_MINUTE;
                    break;
                case SECONDS:
                    ret += DateUtils.MILLIS_PER_SECOND;
                    break;
                default:
                    // Something is malformed just let it fly by and keep going
                    break;
                }
            }
        }
    }
    return ret;
}

From source file:ca.uhn.fhir.jpa.dao.dstu3.FhirResourceDaoSearchParameterDstu3.java

/**
 * This method is called once per minute to perform any required re-indexing. During most passes this will
 * just check and find that there are no resources requiring re-indexing. In that case the method just returns
 * immediately. If the search finds that some resources require reindexing, the system will do a bunch of
 * reindexing and then return.//from  w  ww.  j av  a 2s  .c o  m
 */
@Override
@Scheduled(fixedDelay = DateUtils.MILLIS_PER_MINUTE)
public void performReindexingPass() {
    if (getConfig().isSchedulingDisabled()) {
        return;
    }

    int count = mySystemDao.performReindexingPass(100);
    for (int i = 0; i < 50 && count != 0; i++) {
        count = mySystemDao.performReindexingPass(100);
        try {
            Thread.sleep(DateUtils.MILLIS_PER_SECOND);
        } catch (InterruptedException e) {
            break;
        }
    }

}

From source file:de.tor.tribes.types.DefenseInformation.java

public boolean addSupport(final Village pSource, UnitHolder pUnit, boolean pPrimary, boolean pMultiUse) {
    long runtime = DSCalculator.calculateMoveTimeInMillis(pSource, target, pUnit.getSpeed());
    boolean allowed = false;
    if (getFirstAttack().getTime() - runtime > System.currentTimeMillis() + DateUtils.MILLIS_PER_MINUTE) {
        //high priority
        allowed = true;//from   w  w  w .j  a  v  a2s . co m
    } else if (getLastAttack().getTime() - runtime > System.currentTimeMillis() + DateUtils.MILLIS_PER_MINUTE) {
        //low priority
        allowed = !pPrimary;
    } else {// if (getLastAttack().getTime() - runtime < System.currentTimeMillis() - DateUtils.MILLIS_PER_MINUTE) {
        //impossible
    }
    if (allowed) {
        Object result = CollectionUtils.find(defenses, new Predicate() {

            @Override
            public boolean evaluate(Object o) {
                return ((Defense) o).getSupporter().equals(pSource);
            }
        });
        if (result == null || pMultiUse) {
            defenses.add(new Defense(this, pSource, pUnit));
            return true;
        }
    }
    return false;
}

From source file:com.norconex.commons.lang.time.DurationUtil.java

private static String format(Locale locale, long duration, boolean islong, int maxUnits) {
    int max = Integer.MAX_VALUE;
    if (maxUnits > 0) {
        max = maxUnits;/* w  ww  . j a  v a 2 s. c  om*/
    }
    long days = duration / DateUtils.MILLIS_PER_DAY;
    long accountedMillis = days * DateUtils.MILLIS_PER_DAY;
    long hours = (duration - accountedMillis) / DateUtils.MILLIS_PER_HOUR;
    accountedMillis += (hours * DateUtils.MILLIS_PER_HOUR);
    long mins = (duration - accountedMillis) / DateUtils.MILLIS_PER_MINUTE;
    accountedMillis += (mins * DateUtils.MILLIS_PER_MINUTE);
    long secs = (duration - accountedMillis) / DateUtils.MILLIS_PER_SECOND;
    StringBuilder b = new StringBuilder();
    int unitCount = 0;
    // days
    if (days > 0) {
        b.append(getString(locale, days, "day", islong));
        unitCount++;
    }
    // hours
    if ((hours > 0 || b.length() > 0) && unitCount < max) {
        b.append(getString(locale, hours, "hour", islong));
        unitCount++;
    }
    // minutes
    if ((mins > 0 || b.length() > 0) && unitCount < max) {
        b.append(getString(locale, mins, "minute", islong));
        unitCount++;
    }
    // seconds
    if (unitCount < max) {
        b.append(getString(locale, secs, "second", islong));
    }
    return b.toString().trim();
}

From source file:ca.uhn.fhir.jpa.dao.dstu3.SearchParamRegistryDstu3.java

private void refreshCacheIfNeccesary() {
    long refreshInterval = 60 * DateUtils.MILLIS_PER_MINUTE;
    if (System.currentTimeMillis() - refreshInterval > myLastRefresh) {
        StopWatch sw = new StopWatch();

        Map<String, Map<String, RuntimeSearchParam>> searchParams = new HashMap<String, Map<String, RuntimeSearchParam>>();
        for (Entry<String, Map<String, RuntimeSearchParam>> nextBuiltInEntry : getBuiltInSearchParams()
                .entrySet()) {//w w w  .  j  a v a2s.  c  o m
            for (RuntimeSearchParam nextParam : nextBuiltInEntry.getValue().values()) {
                String nextResourceName = nextBuiltInEntry.getKey();
                getSearchParamMap(searchParams, nextResourceName).put(nextParam.getName(), nextParam);
            }
        }

        IBundleProvider allSearchParamsBp = mySpDao.search(new SearchParameterMap());
        int size = allSearchParamsBp.size();

        // Just in case..
        if (size > 10000) {
            ourLog.warn("Unable to support >10000 search params!");
            size = 10000;
        }

        List<IBaseResource> allSearchParams = allSearchParamsBp.getResources(0, size);
        for (IBaseResource nextResource : allSearchParams) {
            SearchParameter nextSp = (SearchParameter) nextResource;
            RuntimeSearchParam runtimeSp = toRuntimeSp(nextSp);
            if (runtimeSp == null) {
                continue;
            }

            int dotIdx = runtimeSp.getPath().indexOf('.');
            if (dotIdx == -1) {
                ourLog.warn("Can not determine resource type of {}", runtimeSp.getPath());
                continue;
            }
            String resourceType = runtimeSp.getPath().substring(0, dotIdx);

            Map<String, RuntimeSearchParam> searchParamMap = getSearchParamMap(searchParams, resourceType);
            String name = runtimeSp.getName();
            if (myDaoConfig.isDefaultSearchParamsCanBeOverridden() || !searchParamMap.containsKey(name)) {
                searchParamMap.put(name, runtimeSp);
            }
        }

        Map<String, Map<String, RuntimeSearchParam>> activeSearchParams = new HashMap<String, Map<String, RuntimeSearchParam>>();
        for (Entry<String, Map<String, RuntimeSearchParam>> nextEntry : searchParams.entrySet()) {
            for (RuntimeSearchParam nextSp : nextEntry.getValue().values()) {
                String nextName = nextSp.getName();
                if (nextSp.getStatus() != RuntimeSearchParamStatusEnum.ACTIVE) {
                    nextSp = null;
                }

                if (!activeSearchParams.containsKey(nextEntry.getKey())) {
                    activeSearchParams.put(nextEntry.getKey(), new HashMap<String, RuntimeSearchParam>());
                }
                if (activeSearchParams.containsKey(nextEntry.getKey())) {
                    ourLog.debug("Replacing existing/built in search param {}:{} with new one",
                            nextEntry.getKey(), nextName);
                }

                if (nextSp != null) {
                    activeSearchParams.get(nextEntry.getKey()).put(nextName, nextSp);
                } else {
                    activeSearchParams.get(nextEntry.getKey()).remove(nextName);
                }
            }
        }

        myActiveSearchParams = activeSearchParams;

        myLastRefresh = System.currentTimeMillis();
        ourLog.info("Refreshed search parameter cache in {}ms", sw.getMillis());
    }
}

From source file:ca.uhn.fhir.model.primitive.BaseDateTimeDt.java

@Override
protected String encode(Date theValue) {
    if (theValue == null) {
        return null;
    } else {//from   w  w w  .  j a  v  a 2 s  .c  om
        GregorianCalendar cal;
        if (myTimeZoneZulu) {
            cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        } else if (myTimeZone != null) {
            cal = new GregorianCalendar(myTimeZone);
        } else {
            cal = new GregorianCalendar();
        }
        cal.setTime(theValue);

        StringBuilder b = new StringBuilder();
        leftPadWithZeros(cal.get(Calendar.YEAR), 4, b);
        if (myPrecision.ordinal() > TemporalPrecisionEnum.YEAR.ordinal()) {
            b.append('-');
            leftPadWithZeros(cal.get(Calendar.MONTH) + 1, 2, b);
            if (myPrecision.ordinal() > TemporalPrecisionEnum.MONTH.ordinal()) {
                b.append('-');
                leftPadWithZeros(cal.get(Calendar.DATE), 2, b);
                if (myPrecision.ordinal() > TemporalPrecisionEnum.DAY.ordinal()) {
                    b.append('T');
                    leftPadWithZeros(cal.get(Calendar.HOUR_OF_DAY), 2, b);
                    b.append(':');
                    leftPadWithZeros(cal.get(Calendar.MINUTE), 2, b);
                    if (myPrecision.ordinal() > TemporalPrecisionEnum.MINUTE.ordinal()) {
                        b.append(':');
                        leftPadWithZeros(cal.get(Calendar.SECOND), 2, b);
                        if (myPrecision.ordinal() > TemporalPrecisionEnum.SECOND.ordinal()) {
                            b.append('.');
                            b.append(myFractionalSeconds);
                            for (int i = myFractionalSeconds.length(); i < 3; i++) {
                                b.append('0');
                            }
                        }
                    }

                    if (myTimeZoneZulu) {
                        b.append('Z');
                    } else if (myTimeZone != null) {
                        int offset = myTimeZone.getOffset(theValue.getTime());
                        if (offset >= 0) {
                            b.append('+');
                        } else {
                            b.append('-');
                            offset = Math.abs(offset);
                        }

                        int hoursOffset = (int) (offset / DateUtils.MILLIS_PER_HOUR);
                        leftPadWithZeros(hoursOffset, 2, b);
                        b.append(':');
                        int minutesOffset = (int) (offset % DateUtils.MILLIS_PER_HOUR);
                        minutesOffset = (int) (minutesOffset / DateUtils.MILLIS_PER_MINUTE);
                        leftPadWithZeros(minutesOffset, 2, b);
                    }
                }
            }
        }
        return b.toString();
    }
}

From source file:ca.uhn.fhir.jpa.dao.dstu3.FhirResourceDaoSubscriptionDstu3.java

@Scheduled(fixedDelay = DateUtils.MILLIS_PER_MINUTE)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@Override//from   w w w.j a  v a 2  s  .  c o m
public void purgeInactiveSubscriptions() {
    if (getConfig().isSchedulingDisabled()) {
        return;
    }

    Long purgeInactiveAfterMillis = getConfig().getSubscriptionPurgeInactiveAfterMillis();
    if (getConfig().isSubscriptionEnabled() == false || purgeInactiveAfterMillis == null) {
        return;
    }

    Date cutoff = new Date(System.currentTimeMillis() - purgeInactiveAfterMillis);
    Collection<SubscriptionTable> toPurge = mySubscriptionTableDao.findInactiveBeforeCutoff(cutoff);
    for (SubscriptionTable subscriptionTable : toPurge) {

        final IdDt subscriptionId = subscriptionTable.getSubscriptionResource().getIdDt();
        ourLog.info("Deleting inactive subscription {} - Created {}, last client poll {}",
                new Object[] { subscriptionId.toUnqualified(), subscriptionTable.getCreated(),
                        subscriptionTable.getLastClientPoll() });
        TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
        txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        txTemplate.execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus theStatus) {
                delete(subscriptionId, null);
                return null;
            }
        });
    }
}

From source file:de.tor.tribes.types.FarmInformation.java

private void guessResourceBuildings(FightReport pReport) {
    if (pReport == null || pReport.getHaul() == null) {
        // no info
        return;//w w  w  . jav  a  2s .c o m
    }
    // only use if last report is not too old....!! -> send time - 30min !?
    // and if last attack returned empty
    long send = pReport.getTimestamp() - DSCalculator.calculateMoveTimeInMillis(pReport.getSourceVillage(),
            pReport.getTargetVillage(), pReport.getAttackers().getSpeed());

    if (resourcesFoundInLastReport || lastReport == -1 || lastReport < send - 200 * DateUtils.MILLIS_PER_MINUTE
            || lastReport == pReport.getTimestamp()) {
        // ignore this report
        return;
    }

    int wood = pReport.getHaul()[0];
    int clay = pReport.getHaul()[1];
    int iron = pReport.getHaul()[2];

    double dt = (pReport.getTimestamp() - lastReport) / (double) DateUtils.MILLIS_PER_HOUR;
    int woodBuildingLevel = DSCalculator.calculateEstimatedResourceBuildingLevel(wood, dt);
    int clayBuildingLevel = DSCalculator.calculateEstimatedResourceBuildingLevel(clay, dt);
    int ironBuildingLevel = DSCalculator.calculateEstimatedResourceBuildingLevel(iron, dt);
    setBuilding("wood", Math.max(getBuilding("wood"), woodBuildingLevel));
    setBuilding("stone", Math.max(getBuilding("stone"), clayBuildingLevel));
    setBuilding("iron", Math.max(getBuilding("iron"), ironBuildingLevel));
}