Example usage for java.util Calendar before

List of usage examples for java.util Calendar before

Introduction

In this page you can find the example usage for java.util Calendar before.

Prototype

public boolean before(Object when) 

Source Link

Document

Returns whether this Calendar represents a time before the time represented by the specified Object.

Usage

From source file:io.github.tavernaextras.biocatalogue.model.Util.java

/**
 * Calculates time difference between two {@link Calendar} instances.
 * //from ww w  . ja v  a2 s .  co m
 * @param earlier The "earlier" date.
 * @param later The "later" date.
 * @param maxDifferenceMillis The maximum allowed time difference between the two
 *                            {@link Calendar} instances, in milliseconds. If the calculated
 *                            difference will exceed <code>maxDifferenceMillis</code>,
 *                            <code>null</code> will be returned. If this parameter has
 *                            a value <code>less or equal to zero</code>, any time difference
 *                            between the {@link Calendar} instances will be permitted.
 * @return String in the form "XX seconds|minutes|hours|days ago". Proper pluralisation will
 *         be performed on the name of the time unit. <code>null</code> will be returned in
 *         cases where one of the {@link Calendar} instances is <code>null</code>, time
 *         difference between the provided instances is greater than <code>maxDifferenceMillis</code>
 *         or <code>earlier</code> date is not really earlier than <code>later</code> one.
 */
public static String getAgoString(Calendar earlier, Calendar later, long maxDifferenceMillis) {
    // one of the dates is missing
    if (earlier == null || later == null) {
        return null;
    }

    if (earlier.before(later)) {
        long differenceMillis = later.getTimeInMillis() - earlier.getTimeInMillis();

        if (maxDifferenceMillis <= 0 || (maxDifferenceMillis > 0 && differenceMillis <= maxDifferenceMillis)) {
            long result = 0;
            String unitName = "";

            if (differenceMillis < 60 * 1000) {
                result = differenceMillis / 1000;
                unitName = "second";
            } else if (differenceMillis < 60 * 60 * 1000) {
                result = differenceMillis / (60 * 1000);
                unitName = "minute";
            } else if (differenceMillis < 24 * 60 * 60 * 1000) {
                result = differenceMillis / (60 * 60 * 1000);
                unitName = "hour";
            } else {
                result = differenceMillis / (24 * 60 * 60 * 1000);
                unitName = "day";
            }

            return (result + " " + Util.pluraliseNoun(unitName, result, true) + " ago");
        } else {
            // the difference is too large - larger than the supplied threshold
            return null;
        }
    } else {
        // the "later" date is not really later than the "earlier" one
        return null;
    }
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Stop TG server synchronously. //from   ww w  . j a v  a 2 s.  co  m
 * Stop operation blocks until it is completed.
 * 
 * @param tgServer TG server to stop
 * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
 *
 * @return Output console of stop operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String stopServer(TGServer tgServer, String tgNetListenerName, String logFile, String logLevel,
        long timeout) throws TGAdminException {

    if (tgServer == null)
        throw new TGAdminException("TGAdmin - tgServer cannot be null");

    TGServer.NetListener netListener = tgServer.getNetListeners()[0]; // default get the 1st one
    if (tgNetListenerName != null) {
        for (TGServer.NetListener net : tgServer.getNetListeners()) {
            if (net.getName().equals(tgNetListenerName)) {
                netListener = net;
            }
        }
    }

    String host = netListener.getHost();
    int port = netListener.getPort();
    String user = tgServer.getSystemUser();
    String pwd = tgServer.getSystemPwd();
    String url;
    try {
        url = "tcp://" + ((netListener.isIPv6()) ? ("[" + host + ":" + port + "]") : (host + ":" + port));
    } catch (TGGeneralException e) {
        throw new TGAdminException("TGAdmin - " + e.getMessage());
    }
    TGAdmin.showStopServerBanner = false;
    String output = TGAdmin.stopServer(tgServer.getHome().getAbsolutePath(), url, user, pwd, logFile, logLevel,
            3000);

    boolean tgdbRunning = true;
    if (timeout >= 0) {
        Calendar future = Calendar.getInstance();
        future.add(Calendar.MILLISECOND, (int) timeout);
        while (!future.before(Calendar.getInstance())) {
            try {
                Thread.sleep(1000);
                tgdbRunning = ProcessCheck.isProcessRunning(tgServer.getPid());
                if (!tgdbRunning)
                    break;
            } catch (IOException | TGGeneralException | InterruptedException e) {
                throw new TGAdminException("TGAdmin - " + e.getMessage(), output);
            }
        }
    } else { // wait forever for tgdb to stop
        while (true) {
            try {
                Thread.sleep(1000);
                tgdbRunning = ProcessCheck.isProcessRunning(tgServer.getPid());
                if (!tgdbRunning)
                    break;
            } catch (IOException | TGGeneralException | InterruptedException e) {
                throw new TGAdminException("TGAdmin - " + e.getMessage(), output);
            }
        }
    }
    if (tgdbRunning)
        throw new TGAdminException("TGAdmin - Server did not stop on time (after " + timeout + " msec)");

    long endProcTime = System.currentTimeMillis();
    long totalProcTime = endProcTime - TGAdmin.startProcTime;
    System.out.println(
            "TGAdmin - Server stop completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    tgServer.setRunning(false);
    tgServer.setPid(0);
    return output;
}

From source file:com.sammyun.util.DateUtil.java

/**
 * ?// w w  w  .j  av a  2s  .  co  m
 * 
 * @param birthDay 
 * @return
 * @throws Exception
 * @see [?#?#?]
 */
public static Integer getAge(Date birthDay) {
    if (birthDay == null) {
        return 0;
    }
    Calendar cal = Calendar.getInstance();
    if (cal.before(birthDay)) {
        return 0;
    }
    int yearNow = cal.get(Calendar.YEAR);
    int monthNow = cal.get(Calendar.MONTH) + 1;// ??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) {
            if (dayOfMonthNow < dayOfMonthBirth) {
                age--;
            }
        } else if (monthNow < monthBirth) {
            age--;
        }
    } else {
        // monthNow<monthBirth
        // donothing
    }

    return age;
}

From source file:fr.inria.ucn.Helpers.java

/**
 * @param c//from ww  w  .  ja  va2s. c  om
 * @return <code>True</code> if user has enabled the night-time mode and current time is
 * within night, else <code>False</code>.
 */
public static boolean isNightTime(Context c) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
    if (!prefs.getBoolean(Constants.PREF_STOP_NIGHT, false))
        return false;

    int nstart = prefs.getInt(Constants.PREF_NIGHT_START, 23 * 3600);
    int nstop = prefs.getInt(Constants.PREF_NIGHT_STOP, 6 * 3600);

    Calendar nightstart = Calendar.getInstance();
    nightstart.roll(Calendar.HOUR_OF_DAY, -1 * nightstart.get(Calendar.HOUR_OF_DAY));
    nightstart.roll(Calendar.MINUTE, -1 * nightstart.get(Calendar.MINUTE));
    nightstart.roll(Calendar.SECOND, -1 * nightstart.get(Calendar.SECOND));
    nightstart.roll(Calendar.MILLISECOND, -1 * nightstart.get(Calendar.MILLISECOND));
    nightstart.add(Calendar.SECOND, nstart);

    Calendar nightstop = Calendar.getInstance();
    nightstop.roll(Calendar.HOUR_OF_DAY, -1 * nightstop.get(Calendar.HOUR_OF_DAY));
    nightstop.roll(Calendar.MINUTE, -1 * nightstop.get(Calendar.MINUTE));
    nightstop.roll(Calendar.SECOND, -1 * nightstop.get(Calendar.SECOND));
    nightstop.roll(Calendar.MILLISECOND, -1 * nightstop.get(Calendar.MILLISECOND));
    nightstop.add(Calendar.SECOND, nstop);
    if (nightstop.before(nightstart))
        nightstop.add(Calendar.HOUR, 24);

    Log.d(Constants.LOGTAG, "nightstart " + nstart + " -> " + nightstart.toString());
    Log.d(Constants.LOGTAG, "nightstop " + nstop + " -> " + nightstop.toString());

    Calendar now = Calendar.getInstance();
    return (now.after(nightstart) && now.before(nightstop));
}

From source file:fr.inria.ucn.Helpers.java

/**
 * //from   www.j  a  v  a  2s.  c o m
 * @param c
 * @return -1 if not at night-time (or feature disabled), else milliseconds until morning.
 */
public static long getNightEnd(Context c) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
    if (!prefs.getBoolean(Constants.PREF_STOP_NIGHT, false))
        return -1;

    int nstart = prefs.getInt(Constants.PREF_NIGHT_START, 23 * 3600);
    int nstop = prefs.getInt(Constants.PREF_NIGHT_STOP, 6 * 3600);

    Calendar nightstart = Calendar.getInstance();
    nightstart.roll(Calendar.HOUR_OF_DAY, -1 * nightstart.get(Calendar.HOUR_OF_DAY));
    nightstart.roll(Calendar.MINUTE, -1 * nightstart.get(Calendar.MINUTE));
    nightstart.roll(Calendar.SECOND, -1 * nightstart.get(Calendar.SECOND));
    nightstart.roll(Calendar.MILLISECOND, -1 * nightstart.get(Calendar.MILLISECOND));
    nightstart.add(Calendar.SECOND, nstart);

    Calendar nightstop = Calendar.getInstance();
    nightstop.roll(Calendar.HOUR_OF_DAY, -1 * nightstop.get(Calendar.HOUR_OF_DAY));
    nightstop.roll(Calendar.MINUTE, -1 * nightstop.get(Calendar.MINUTE));
    nightstop.roll(Calendar.SECOND, -1 * nightstop.get(Calendar.SECOND));
    nightstop.roll(Calendar.MILLISECOND, -1 * nightstop.get(Calendar.MILLISECOND));
    nightstop.add(Calendar.SECOND, nstop);
    if (nightstop.before(nightstart))
        nightstop.add(Calendar.HOUR, 24);

    Log.d(Constants.LOGTAG, "nightstart " + nstart + " -> " + nightstart.toString());
    Log.d(Constants.LOGTAG, "nightstop " + nstop + " -> " + nightstop.toString());

    Calendar now = Calendar.getInstance();
    if (now.after(nightstart) && now.before(nightstop)) {
        return nightstop.getTimeInMillis();
    } else {
        return -1;
    }
}

From source file:org.eyeseetea.malariacare.network.ServerAPIController.java

/**
 * compares the dates of the surveys and checks if the dates are over the limit
 * @param surveyList all the sent surveys
 * @return true if the surveys are over the limit
 *//*from   w  w  w . java 2s  . c  o  m*/
static boolean isSurveyOverLimit(List<Survey> surveyList) {
    if (surveyList.size() >= DHIS_LIMIT_SENT_SURVEYS_IN_ONE_HOUR) {
        for (int i = 0; i < surveyList.size(); i++) {
            int countDates = 0;
            Calendar actualSurvey = Utils.DateToCalendar(surveyList.get(i).getEventDate());
            for (int d = 0; d < surveyList.size(); d++) {
                Calendar nextSurvey = Utils.DateToCalendar(surveyList.get(d).getEventDate());
                if (actualSurvey.before(nextSurvey)) {
                    if (!Utils.isDateOverLimit(actualSurvey, nextSurvey, DHIS_LIMIT_HOURS)) {
                        countDates++;
                        Log.d(TAG, "Surveys sents in one hour:" + countDates);
                        if (countDates >= DHIS_LIMIT_SENT_SURVEYS_IN_ONE_HOUR) {
                            return true;
                        }
                    }
                }
            }
        }
    }
    return false;
}

From source file:CalendarComparator.java

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;/*from www  . ja  v a 2  s  .c om*/
}

From source file:cloudnet.weather.data.forecastio.WeatherDataFetcher.java

public void fetchData(String locationData, String city, Calendar start, Calendar end) {

    try {/*from   www. jav  a  2s  .  co  m*/
        URL url;
        while (start.before(end)) {
            url = new URL(urlString + locationData + "," + start.getTimeInMillis() / 1000 + "?units=si");
            File file = new File("resources/weather/" + city + "/" + start.getTimeInMillis() / 1000 + ".json");
            LOGGER.trace("downloading " + start.getTimeInMillis() / 1000);
            FileUtils.copyURLToFile(url, file);
            start.add(Calendar.HOUR, 12);
        }

    } catch (MalformedURLException e) {
        LOGGER.error("fetchData", e);
    } catch (IOException e) {
        LOGGER.error("fetchData", e);
    }
}

From source file:com.krawler.common.util.BaseStringUtil.java

public static Boolean isLessthanDates(java.util.Date olddate, Date newdate) {
    boolean flag = false;
    try {//from   w ww .ja  v  a  2s.  c  o m
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar olddt = Calendar.getInstance();
        olddt.setTime(sdf.parse(sdf.format(olddate)));

        Calendar newdt = Calendar.getInstance();
        newdt.setTime(sdf.parse(sdf.format(newdate)));
        flag = olddt.before(newdt);
    } catch (ParseException ex) {
        LOG.info("Can't parse the date in isLessthanDates() : ", ex);
    }
    return flag;
}

From source file:com.sean.takeastand.alarmprocess.AlarmReceiver.java

private boolean hasEndTimePassed(Calendar endTime) {
    Calendar rightNow = Calendar.getInstance();
    return endTime.before(rightNow);
}