Example usage for java.util Calendar compareTo

List of usage examples for java.util Calendar compareTo

Introduction

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

Prototype

private int compareTo(long t) 

Source Link

Usage

From source file:com.androidinspain.deskclock.Utils.java

/**
 * Given a point in time, return the subsequent moment any of the time zones changes days.
 * e.g. Given 8:00pm on 1/1/2016 and time zones in LA and NY this method would return a Date for
 * midnight on 1/2/2016 in the NY timezone since it changes days first.
 *
 * @param time  a point in time from which to compute midnight on the subsequent day
 * @param zones a collection of time zones
 * @return the nearest point in the future at which any of the time zones changes days
 *//*w  ww.  j a  va2  s.  c o  m*/
public static Date getNextDay(Date time, Collection<TimeZone> zones) {
    Calendar next = null;
    for (TimeZone tz : zones) {
        final Calendar c = Calendar.getInstance(tz);
        c.setTime(time);

        // Advance to the next day.
        c.add(Calendar.DAY_OF_YEAR, 1);

        // Reset the time to midnight.
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        if (next == null || c.compareTo(next) < 0) {
            next = c;
        }
    }

    return next == null ? null : next.getTime();
}

From source file:com.clustercontrol.systemlog.bean.SyslogMessage.java

/**
 * syslog????????SyslogMessage????API<br>
 * <br>//from w  w  w  .  j av  a  2 s.  c o m
 * <b>???</b><br>
 * 1. ???????????????<br>
 * 2. ???????????<br>
 * @param syslog syslog?
 * @return SyslogMessage
 * @throws ParseException syslog???????????
 * @throws HinemosUnknown 
 */
public static SyslogMessage parse(String syslog) throws ParseException, HinemosUnknown {
    if (log.isDebugEnabled()) {
        log.debug("parsing syslog : " + syslog);
    }

    // [0]:, [1]:(MMM), [2]:(dd), [3]:(HH), [4]:(mm), [5]:(ss), [6]:??, [7]:
    // ?{1,date,MMM dd HH:mm:ss}????????????1970????
    // ????????2/29???3/1?????(1970???????)
    MessageFormat syslogFormat = new MessageFormat("<{0,number,integer}>{1} {2} {3}:{4}:{5} {6} {7}",
            Locale.ENGLISH);

    // ??????
    Object[] syslogArgs = syslogFormat.parse(syslog);

    // RFC3164??????????????????
    if ("".equals(syslogArgs[SYSLOG_FORMAT_DAY])) {
        syslogFormat = new MessageFormat("<{0,number,integer}>{1}  {2} {3}:{4}:{5} {6} {7}", Locale.ENGLISH);
        syslogArgs = syslogFormat.parse(syslog);
    }

    if (syslogArgs == null)
        throw new HinemosUnknown("different syslog pattern");

    if (log.isDebugEnabled()) {
        int i = 0;
        for (Object arg : syslogArgs) {
            log.debug(String.format("syslog args [%d] : %s", i++, arg.toString()));
        }
    }

    // ???????(H)
    Integer syslogEffectiveTime = HinemosPropertyUtil
            .getHinemosPropertyNum("monitor.systemlog.period.hour", Long.valueOf(SYSLOG_DEFAULT_PERIOD_HOUR))
            .intValue();

    // 0???????????
    if (syslogEffectiveTime <= 0) {
        syslogEffectiveTime = SYSLOG_DEFAULT_PERIOD_HOUR;
    }

    Calendar nowCal = HinemosTime.getCalendarInstance();

    // ??(?)
    int year = nowCal.get(Calendar.YEAR) + 1;
    int month = editCalendarMonth((String) syslogArgs[SYSLOG_FORMAT_MONTH]);
    int dayOfMonth = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_DAY]);
    int hourOfDay = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_HH]);
    int minute = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_MM]);
    int second = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_SS]);

    // ?
    List<Calendar> checkCalList = new ArrayList<Calendar>();
    // (??
    Calendar syslogEffectiveCal = (Calendar) nowCal.clone();
    syslogEffectiveCal.add(Calendar.HOUR, syslogEffectiveTime);

    // ???
    for (int i = 0; checkCalList.size() < 2; i++) {

        // ??????
        if (LEAPYEAR_CHECK_COUNT <= i) {
            break;
        }
        Calendar syslogCheckCal = new GregorianCalendar(year, month, dayOfMonth, hourOfDay, minute, second);
        year--;

        // ???????(??)
        if (syslogEffectiveCal.compareTo(syslogCheckCal) < 0) {
            continue;
        }
        // ??????????????
        if (dayOfMonth != syslogCheckCal.get(Calendar.DAY_OF_MONTH)) {
            continue;
        }
        // ????
        checkCalList.add(syslogCheckCal);
    }

    Calendar editSyslogCal = null;

    // ?????
    if (checkCalList.size() > 0) {
        long absMinMillis = Long.MAX_VALUE;
        for (int i = 0; i < checkCalList.size(); i++) {
            long absDiff = Math.abs(checkCalList.get(i).getTimeInMillis() - nowCal.getTimeInMillis());
            if (absDiff < absMinMillis) {
                // ??????
                absMinMillis = absDiff;
                editSyslogCal = checkCalList.get(i);
            }
        }
    } else {
        // ??????
        editSyslogCal = new GregorianCalendar(nowCal.get(Calendar.YEAR), month, dayOfMonth, hourOfDay, minute,
                second);
        log.warn("System log date is invalid : " + syslog);
    }

    int pri = ((Long) syslogArgs[SYSLOG_FORMAT_PRIORITY]).intValue();
    String hostname = (String) syslogArgs[SYSLOG_FORMAT_HOSTNAME];
    String msg = (String) syslogArgs[SYSLOG_FORMAT_MESSAGE];
    Date date = editSyslogCal.getTime();

    // ??
    SyslogMessage instance = new SyslogMessage(getFacility((int) pri), getSeverity((int) pri), date.getTime(),
            hostname, msg, syslog);
    if (log.isDebugEnabled()) {
        log.debug("parsed syslog : " + instance);
    }

    return instance;
}

From source file:org.wikipedia.nirvana.archive.ArchiveSimpleSorted.java

/**
 * //from   w  ww .j  a v  a 2s  . com
 */
public ArchiveSimpleSorted(NirvanaWiki wiki, String lines[], boolean addToTop, String delimeter) {
    super(addToTop, delimeter);
    this.wiki = wiki;
    Comparator<Calendar> compA = new Comparator<Calendar>() {
        @Override
        public int compare(Calendar a, Calendar b) {
            return a.compareTo(b);
        }
    };
    Comparator<Calendar> compB = new Comparator<Calendar>() {
        @Override
        public int compare(Calendar a, Calendar b) {
            return b.compareTo(a);
        }
    };
    if (addToTop)
        itemsSorted = new TreeMap<Calendar, String>(compB); // descending
    else
        itemsSorted = new TreeMap<Calendar, String>(compA); // ascending
    for (String line : lines) {
        add(line);
    }
}

From source file:hudson.plugins.vcloud.VCDConnection.java

private boolean sessionExpired() {
    Calendar now = Calendar.getInstance();
    return now.compareTo(getTimeout()) >= 0;
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.StartDateBeforeEndDate.java

private Map<String, String> checkDateLiterals(Literal startLit, Literal endLit) {
    Map<String, String> errors = new HashMap<String, String>();
    Calendar startDate = getDateFromLiteral(startLit);
    Calendar endDate = getDateFromLiteral(endLit);
    try {/*from  w w w  . ja v a  2  s.c  om*/
        if (startDate.compareTo(endDate) > 0) {
            errors.put(startFieldName, "Start date cannot follow end date");
            errors.put(endFieldName, "End date cannot precede start date");
        }
    } catch (NullPointerException npe) {
        log.error("Cannot compare date to null.");

    } catch (IllegalArgumentException iae) {
        log.error("IllegalArgumentException");
    }
    return errors;
}

From source file:br.com.transport.report.ManagerReportBean.java

/**
 * Retira da lista de dias da semana os dias utilizados no frete
 * @param mapReport/*from  ww  w.  ja  v a 2 s . co  m*/
 * @param handlerList
 */
private void removeDays(Map<Long, List<Calendar>> mapReport, List<ReportVO> handlerList) {

    Calendar init = getInitCalendar();

    Calendar end = getInitCalendar();

    for (ReportVO report : handlerList) {

        List<Calendar> daysList = new LinkedList<Calendar>(mapReport.get(report.getCarrierId()));

        init.setTime(report.getDepartureDate());
        end.setTime(report.getDeliveryDate());

        for (Calendar cld : daysList) {
            if (cld.compareTo(init) == 0 || (cld.after(init) && (cld.before(end) || cld.compareTo(end) == 0))) {
                mapReport.get(report.getCarrierId()).remove(cld);
            }
        }
    }
}

From source file:com.atolcd.alfresco.audit.web.scripts.ExportGet.java

private boolean testParameters(String s_start, String s_end) {
    if (s_start != null && s_end != null) {

        Calendar start = getDateFromString(s_start, "-");
        Calendar end = getDateFromString(s_end, "-");

        if (start.compareTo(end) < 0) {
            setStartDate(start);/*from   w  w w.j  a v a 2 s. c o m*/
            setEndDate(end);
        } else {
            setStartDate(end);
            setEndDate(start);
        }

        return true;
    }

    return false;
}

From source file:org.broadleafcommerce.cms.web.file.StaticAssetView.java

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String cacheFilePath = (String) model.get("cacheFilePath");
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(cacheFilePath));
    try {/*from   w w  w.  ja v  a 2  s.c  o m*/
        String mimeType = (String) model.get("mimeType");
        response.setContentType(mimeType);
        if (!browserAssetCachingEnabled) {
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
        } else {
            response.setHeader("Cache-Control", "public");
            response.setHeader("Pragma", "cache");
            if (!StringUtils.isEmpty(request.getHeader("If-Modified-Since"))) {
                long lastModified = request.getDateHeader("If-Modified-Since");
                Calendar last = Calendar.getInstance();
                last.setTime(new Date(lastModified));
                Calendar check = Calendar.getInstance();
                check.add(Calendar.SECOND, -2 * new Long(cacheSeconds).intValue());
                if (check.compareTo(last) < 0) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
            } else {
                Calendar check = Calendar.getInstance();
                check.add(Calendar.SECOND, -1 * new Long(cacheSeconds).intValue());
                response.setDateHeader("Last-Modified", check.getTimeInMillis());
            }
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, new Long(cacheSeconds).intValue());
            response.setDateHeader("Expires", cal.getTimeInMillis());
        }
        OutputStream os = response.getOutputStream();
        boolean eof = false;
        while (!eof) {
            int temp = bis.read();
            if (temp < 0) {
                eof = true;
            } else {
                os.write(temp);
            }
        }
        os.flush();
    } catch (Exception e) {
        if (e.getCause() instanceof SocketException) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Unable to stream asset", e);
            }
        } else {
            LOG.error("Unable to stream asset", e);
            throw e;
        }
    } finally {
        try {
            bis.close();
        } catch (Throwable e) {
            //do nothing
        }
    }
}

From source file:org.flowable.standalone.calendar.DurationHelperTest.java

@Test
public void daylightSavingFallObservedFirstHour() throws Exception {
    Clock testingClock = new DefaultClockImpl();
    testingClock.setCurrentCalendar(parseCalendar("20131103-00:45:00", TimeZone.getTimeZone("US/Eastern")));

    DurationHelper dh = new DurationHelper("R2/2013-11-03T00:45:00-04:00/PT1H", testingClock);
    Calendar expected = parseCalendarWithOffset("20131103-01:45:00 -04:00", TimeZone.getTimeZone("US/Eastern"));

    assertTrue(expected.compareTo(dh.getCalendarAfter()) == 0);
}

From source file:org.flowable.standalone.calendar.DurationHelperTest.java

@Test
public void daylightSavingFallObservedSecondHour() throws Exception {
    Clock testingClock = new DefaultClockImpl();
    testingClock.setCurrentCalendar(parseCalendar("20131103-00:45:00", TimeZone.getTimeZone("US/Eastern")));

    DurationHelper dh = new DurationHelper("R2/2013-11-03T00:45:00-04:00/PT2H", testingClock);
    Calendar expected = parseCalendarWithOffset("20131103-01:45:00 -05:00", TimeZone.getTimeZone("US/Eastern"));

    assertTrue(expected.compareTo(dh.getCalendarAfter()) == 0);
}