Example usage for java.util Calendar HOUR

List of usage examples for java.util Calendar HOUR

Introduction

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

Prototype

int HOUR

To view the source code for java.util Calendar HOUR.

Click Source Link

Document

Field number for get and set indicating the hour of the morning or afternoon.

Usage

From source file:org.motechproject.mobile.itests.MessageServiceImplITCase.java

/**
 * Test of sendPatientMessages method, of class MessageServiceImpl.
 *///from w w  w . java 2  s  .  co  m
@Test
public void testSendPatientMessages() {
    System.out.println("sendPatientMessages");

    Date date = new Date();
    Calendar cal = Calendar.getInstance();

    PatientMessage msg1 = new PatientMessage();
    msg1.setMessageId("testId1");
    NameValuePair attrib1 = new NameValuePair("PatientFirstName", "Tester1");
    NameValuePair attrib2 = new NameValuePair("DueDate", "now");
    msg1.setPersonalInfo(new NameValuePair[] { attrib1, attrib2 });
    msg1.setStartDate(date);
    cal.add(Calendar.HOUR, 1);
    msg1.setEndDate(cal.getTime());
    msg1.setPatientNumber("0900000001");
    msg1.setPatientNumberType(ContactNumberType.PERSONAL);
    msg1.setMediaType(MediaType.TEXT);
    msg1.setLangCode("en");
    msg1.setNotificationType(2L);
    msg1.setRecipientId("1234567");

    PatientMessage msg2 = new PatientMessage();
    msg1.setMessageId("testId1");
    NameValuePair attrib3 = new NameValuePair("PatientFirstName", "Tester2");
    NameValuePair attrib4 = new NameValuePair("DueDate", "now");
    msg1.setPersonalInfo(new NameValuePair[] { attrib3, attrib4 });
    msg1.setStartDate(date);
    cal.setTime(date);
    cal.add(Calendar.HOUR, 1);
    msg1.setEndDate(cal.getTime());
    msg1.setPatientNumber("0900000002");
    msg1.setPatientNumberType(ContactNumberType.HOUSEHOLD);
    msg1.setMediaType(MediaType.VOICE);
    msg1.setLangCode("en");
    msg1.setNotificationType(2L);
    msg1.setRecipientId("1234568");

    PatientMessage[] messages = new PatientMessage[] { msg1, msg2 };

    client.sendPatientMessages(messages);
}

From source file:de.berlios.statcvs.xml.report.CommitActivityChart.java

private void addToXYSeries(XYSeries series, CvsRevision rev) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(rev.getDate());//from  w  ww.  j a va  2  s .c o m
    double hour = cal.get(Calendar.HOUR_OF_DAY);
    double minutes = cal.get(Calendar.MINUTE);

    // clear time info
    cal.clear(Calendar.HOUR);
    cal.clear(Calendar.HOUR_OF_DAY);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MILLISECOND);

    series.add(cal.getTime().getTime(), hour + (minutes / 60));
}

From source file:org.ambraproject.BaseTest.java

/**
 * Helper method to compare dates.  This compares down to the minute, and checks that the seconds are within 1, since
 * rounding can occur when storing to an hsql db
 *
 * @param actual   - the date from mysql to compare
 * @param expected - the date from topaz to compare
 *//*from  w ww.ja  v a2s.c  o  m*/
protected static void assertMatchingDates(Date actual, Date expected) {
    if (actual == null || expected == null) {
        assertTrue(actual == null && expected == null, "one date was null and the other wasn't");
    } else {
        Calendar actualCal = new GregorianCalendar();
        actualCal.setTime(actual);
        Calendar expectedCal = new GregorianCalendar();
        expectedCal.setTime(expected);
        assertEquals(actualCal.get(Calendar.YEAR), expectedCal.get(Calendar.YEAR),
                "Dates didn't have matching years");
        assertEquals(actualCal.get(Calendar.MONTH), expectedCal.get(Calendar.MONTH),
                "dates didn't have matching months");
        assertEquals(actualCal.get(Calendar.DAY_OF_MONTH), expectedCal.get(Calendar.DAY_OF_MONTH),
                "dates didn't have matching days of month");
        assertEquals(actualCal.get(Calendar.DAY_OF_WEEK), expectedCal.get(Calendar.DAY_OF_WEEK),
                "dates didn't have matching days of week");
        assertEquals(actualCal.get(Calendar.HOUR), expectedCal.get(Calendar.HOUR),
                "dates didn't have matching hours");
        assertEquals(actualCal.get(Calendar.MINUTE), expectedCal.get(Calendar.MINUTE),
                "dates didn't have matching minutes");
        int secondMin = expectedCal.get(Calendar.SECOND) - 1;
        int secondMax = expectedCal.get(Calendar.SECOND) + 1;
        int actualSecond = actualCal.get(Calendar.SECOND);
        assertTrue(secondMin <= actualSecond && actualSecond <= secondMax,
                "date didn't have correct second; expected something in [" + secondMin + "," + secondMax
                        + "]; but got " + actualSecond);
    }
}

From source file:com.appeligo.captions.DeleteOldProgramsThread.java

@Override
public void run() {

    while (true) {
        LuceneIndexer liveIndex = LuceneIndexer.getInstance(liveIndexLocation);
        Calendar wayback = Calendar.getInstance();
        wayback.add(Calendar.MONTH, -3);
        Calendar tenminutesago = Calendar.getInstance();
        tenminutesago.add(Calendar.MINUTE, -10);
        log.info("Deleting old programs from live index, between " + wayback.getTime() + " and "
                + tenminutesago.getTime());
        String dateField = "lineup-" + liveLineup + "-endTime";
        ConstantScoreRangeQuery dateQuery = new ConstantScoreRangeQuery(dateField,
                DateTools.dateToString(wayback.getTime(), DateTools.Resolution.MINUTE),
                DateTools.dateToString(tenminutesago.getTime(), DateTools.Resolution.MINUTE), true, true);
        IndexSearcher searcher = null;/*  ww  w  .  j  a va 2 s . c o  m*/
        try {
            searcher = new IndexSearcher(liveIndexLocation);
            Hits hits = searcher.search(dateQuery);
            Set<Term> terms = new HashSet<Term>();
            if (hits.length() > 0) {
                for (int index = 0; index < hits.length(); index++) {
                    Document doc = hits.doc(index);
                    Term term = new Term(dateField, doc.get(dateField));
                    terms.add(term);
                }
            }
            liveIndex.deleteDocuments(terms.toArray(new Term[terms.size()]));
        } catch (IOException e) {
            log.error("Error deleting old programs from live index", e);
        } finally {
            if (searcher != null) {
                try {
                    searcher.close();
                } catch (IOException e) {
                    log.error("Error closing searcher when deleting old programs from live index", e);

                }
            }
        }

        Calendar cal = Calendar.getInstance();
        int minute = cal.get(Calendar.MINUTE);
        if (minute < 15) {
            cal.set(Calendar.MINUTE, 15);
        } else if (minute >= 45) {
            cal.set(Calendar.MINUTE, 15);
            cal.add(Calendar.HOUR, 1);
        } else {
            cal.set(Calendar.MINUTE, 45);
        }
        log.info("queued up that delete, now we're waiting until " + cal.getTime());
        Utils.sleepUntil(cal.getTimeInMillis());
    }
}

From source file:com.maydesk.base.util.PDUtil.java

public static boolean isBefore(Date date1, Date date2) {
    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(date1);/*from ww  w  .  ja  v  a2 s.co m*/
    cal1.set(Calendar.HOUR, 0);
    cal1.set(Calendar.MINUTE, 0);
    cal1.set(Calendar.SECOND, 0);
    Calendar cal2 = Calendar.getInstance();
    cal1.setTime(date1);
    cal1.set(Calendar.HOUR, 0);
    cal1.set(Calendar.MINUTE, 0);
    cal1.set(Calendar.SECOND, 0);
    return cal1.before(cal2);
}

From source file:DateParser.java

private static Calendar getCalendar(String isodate) {
    // YYYY-MM-DDThh:mm:ss.sTZD
    StringTokenizer st = new StringTokenizer(isodate, "-T:.+Z", true);

    Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.clear();/* w  w  w . j  a  v  a 2  s .  com*/
    try {
        // Year
        if (st.hasMoreTokens()) {
            int year = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.YEAR, year);
        } else {
            return calendar;
        }
        // Month
        if (check(st, "-") && (st.hasMoreTokens())) {
            int month = Integer.parseInt(st.nextToken()) - 1;
            calendar.set(Calendar.MONTH, month);
        } else {
            return calendar;
        }
        // Day
        if (check(st, "-") && (st.hasMoreTokens())) {
            int day = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.DAY_OF_MONTH, day);
        } else {
            return calendar;
        }
        // Hour
        if (check(st, "T") && (st.hasMoreTokens())) {
            int hour = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.HOUR_OF_DAY, hour);
        } else {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            return calendar;
        }
        // Minutes
        if (check(st, ":") && (st.hasMoreTokens())) {
            int minutes = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.MINUTE, minutes);
        } else {
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            return calendar;
        }

        //
        // Not mandatory now
        //

        // Secondes
        if (!st.hasMoreTokens()) {
            return calendar;
        }
        String tok = st.nextToken();
        if (tok.equals(":")) { // secondes
            if (st.hasMoreTokens()) {
                int secondes = Integer.parseInt(st.nextToken());
                calendar.set(Calendar.SECOND, secondes);
                if (!st.hasMoreTokens()) {
                    return calendar;
                }
                // frac sec
                tok = st.nextToken();
                if (tok.equals(".")) {
                    // bug fixed, thx to Martin Bottcher
                    String nt = st.nextToken();
                    while (nt.length() < 3) {
                        nt += "0";
                    }
                    nt = nt.substring(0, 3); // Cut trailing chars..
                    int millisec = Integer.parseInt(nt);
                    // int millisec = Integer.parseInt(st.nextToken()) * 10;
                    calendar.set(Calendar.MILLISECOND, millisec);
                    if (!st.hasMoreTokens()) {
                        return calendar;
                    }
                    tok = st.nextToken();
                } else {
                    calendar.set(Calendar.MILLISECOND, 0);
                }
            } else {
                throw new RuntimeException("No secondes specified");
            }
        } else {
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        }
        // Timezone
        if (!tok.equals("Z")) { // UTC
            if (!(tok.equals("+") || tok.equals("-"))) {
                throw new RuntimeException("only Z, + or - allowed");
            }
            boolean plus = tok.equals("+");
            if (!st.hasMoreTokens()) {
                throw new RuntimeException("Missing hour field");
            }
            int tzhour = Integer.parseInt(st.nextToken());
            int tzmin = 0;
            if (check(st, ":") && (st.hasMoreTokens())) {
                tzmin = Integer.parseInt(st.nextToken());
            } else {
                throw new RuntimeException("Missing minute field");
            }
            if (plus) {
                calendar.add(Calendar.HOUR, -tzhour);
                calendar.add(Calendar.MINUTE, -tzmin);
            } else {
                calendar.add(Calendar.HOUR, tzhour);
                calendar.add(Calendar.MINUTE, tzmin);
            }
        }
    } catch (NumberFormatException ex) {
        throw new RuntimeException("[" + ex.getMessage() + "] is not an integer");
    }
    return calendar;
}

From source file:com.seyren.core.service.notification.HttpNotificationService.java

private String getTimeFromUntilString(Date date) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat format = new SimpleDateFormat("HH:mm_yyyyMMdd");
    cal.setTime(date);/* w  w w .j  ava2  s .c o  m*/
    cal.add(Calendar.HOUR, -1);
    String from = format.format(cal.getTime());
    cal.add(Calendar.HOUR, 1);
    String until = format.format(cal.getTime());

    return "&from=" + until + "&until=" + from;
}

From source file:com.mycompany.CRMFly.serviceLayer.ClientsServiceImpl.java

@Transactional
public Map<Date, Double> getSumsFotDates(Clients client) {
    Long id = client.getId();/*from   www . jav  a2s .c  o  m*/

    Calendar calendar = new GregorianCalendar();
    Integer monthDifference = 0;
    if (calendar.get(Calendar.MONTH) == Calendar.JANUARY || calendar.get(Calendar.MONTH) == Calendar.APRIL
            || calendar.get(Calendar.MONTH) == Calendar.JULY
            || calendar.get(Calendar.MONTH) == Calendar.OCTOBER) {
        monthDifference = 0;
    } else if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY || calendar.get(Calendar.MONTH) == Calendar.MAY
            || calendar.get(Calendar.MONTH) == Calendar.AUGUST
            || calendar.get(Calendar.MONTH) == Calendar.NOVEMBER) {
        monthDifference = -1;
    } else if (calendar.get(Calendar.MONTH) == Calendar.MARCH || calendar.get(Calendar.MONTH) == Calendar.JUNE
            || calendar.get(Calendar.MONTH) == Calendar.SEPTEMBER
            || calendar.get(Calendar.MONTH) == Calendar.DECEMBER)
        monthDifference = -2;
    //     Integer dayDifference = -calendar.get(Calendar.DAY_OF_MONTH);
    calendar.add(Calendar.MONTH, monthDifference);
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    //      calendar.add(Calendar.DAY_OF_MONTH, dayDifference-1);

    Date beginningOfQuarter = calendar.getTime();
    Double thisQuarterSum = 0.0;
    calendar.add(Calendar.MONTH, -3);
    Date QuarterBackOne = calendar.getTime();
    Double QuarterBackOneSum = 0.0;
    calendar.add(Calendar.MONTH, -3);
    Date QuarterBackTwo = calendar.getTime();
    Double QuarterBackTwoSum = 0.0;
    calendar.add(Calendar.MONTH, -3);
    Date QuarterBackThree = calendar.getTime();
    Double QuarterBackThreeSum = 0.0;

    List<Contracts> contracts = clientsDAO.getContractsForClient(id);
    HashMap<Date, Double> sums = new HashMap<Date, Double>();
    for (Contracts contract : contracts) {
        Date date = contract.getBegin_date();
        if (date.after(beginningOfQuarter))
            thisQuarterSum += contract.getTotalSum();
        else if (date.after(QuarterBackOne))
            QuarterBackOneSum += contract.getTotalSum();
        else if (date.after(QuarterBackTwo))
            QuarterBackTwoSum += contract.getTotalSum();
        else if (date.after(QuarterBackThree))
            QuarterBackThreeSum += contract.getTotalSum();
    }
    sums.put(beginningOfQuarter, thisQuarterSum);
    sums.put(QuarterBackOne, QuarterBackOneSum);
    sums.put(QuarterBackTwo, QuarterBackTwoSum);
    sums.put(QuarterBackThree, QuarterBackThreeSum);
    return sums;
}

From source file:com.frey.repo.DateUtil.java

/**
 * ???/*from   w w  w  .j av a2s.co  m*/
 *
 * @return Date
 */
public static Date curDate5() throws ParseException {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}

From source file:net.sourceforge.eclipsetrader.yahoo.HistoryFeed.java

public void updateHistory(Security security, int interval) {
    if (interval == IHistoryFeed.INTERVAL_DAILY) {
        Calendar from = Calendar.getInstance();
        Calendar to = Calendar.getInstance();

        History history = security.getHistory();
        if (history.size() == 0)
            from.add(Calendar.YEAR, -CorePlugin.getDefault().getPreferenceStore()
                    .getInt(CorePlugin.PREFS_HISTORICAL_PRICE_RANGE));
        else {/*  w ww . jav a2 s  .c o  m*/
            Bar cd = history.getLast();
            if (cd != null) {
                from.setTime(cd.getDate());
                from.add(Calendar.DATE, 1);
            }
        }

        try {
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            String host = "ichart.finance.yahoo.com"; //$NON-NLS-1$
            BundleContext context = YahooPlugin.getDefault().getBundle().getBundleContext();
            ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
            if (reference != null) {
                IProxyService proxy = (IProxyService) context.getService(reference);
                IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
                if (data != null) {
                    if (data.getHost() != null)
                        client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                    if (data.isRequiresAuthentication())
                        client.getState().setProxyCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
                }
            }

            String symbol = null;
            if (security.getHistoryFeed() != null)
                symbol = security.getHistoryFeed().getSymbol();
            if (symbol == null || symbol.length() == 0)
                symbol = security.getCode();

            // If the last bar from the data is from a date before today, then
            // download the historical data, otherwise it's enough to download the data for today.
            to.add(Calendar.DAY_OF_MONTH, -1);
            to.set(Calendar.HOUR, 0);
            to.set(Calendar.MINUTE, 0);
            to.set(Calendar.SECOND, 0);
            to.set(Calendar.MILLISECOND, 0);
            Bar lastHistoryBar = history.getLast();
            Date lastDate;
            if (lastHistoryBar == null)
                lastDate = from.getTime();
            else
                lastDate = lastHistoryBar.getDate();
            if (lastDate.before(to.getTime())) {
                log.info("Updating historical data for " + security.getCode() + " - " //$NON-NLS-1$//$NON-NLS-2$
                        + security.getDescription());

                StringBuffer url = new StringBuffer("http://" + host + "/table.csv" + "?s="); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                url.append(symbol);
                url.append("&d=" + to.get(Calendar.MONTH) + "&e=" + to.get(Calendar.DAY_OF_MONTH) + "&f=" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                        + to.get(Calendar.YEAR));
                url.append("&g=d"); //$NON-NLS-1$
                url.append("&a=" + from.get(Calendar.MONTH) + "&b=" + from.get(Calendar.DAY_OF_MONTH) + "&c=" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                        + from.get(Calendar.YEAR));
                url.append("&ignore=.csv"); //$NON-NLS-1$
                log.debug(url);

                HttpMethod method = new GetMethod(url.toString());
                method.setFollowRedirects(true);
                client.executeMethod(method);

                BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));

                // The first line is the header, ignoring
                String inputLine = in.readLine();
                log.trace(inputLine);

                while ((inputLine = in.readLine()) != null) {
                    log.trace(inputLine);
                    if (inputLine.startsWith("<")) //$NON-NLS-1$
                        continue;
                    String[] item = inputLine.split(","); //$NON-NLS-1$
                    if (item.length < 6)
                        continue;

                    Calendar day = Calendar.getInstance();
                    try {
                        day.setTime(df.parse(item[0]));
                    } catch (Exception e) {
                        try {
                            day.setTime(dfAlt.parse(item[0]));
                        } catch (Exception e1) {
                            log.error(e1, e1);
                        }
                    }
                    day.set(Calendar.HOUR, 0);
                    day.set(Calendar.MINUTE, 0);
                    day.set(Calendar.SECOND, 0);
                    day.set(Calendar.MILLISECOND, 0);

                    Bar bar = new Bar();
                    bar.setDate(day.getTime());
                    bar.setOpen(Double.parseDouble(item[1].replace(',', '.')));
                    bar.setHigh(Double.parseDouble(item[2].replace(',', '.')));
                    bar.setLow(Double.parseDouble(item[3].replace(',', '.')));
                    bar.setClose(Double.parseDouble(item[4].replace(',', '.')));
                    bar.setVolume(Long.parseLong(item[5]));

                    // Remove the old bar, if exists
                    int index = history.indexOf(bar.getDate());
                    if (index != -1)
                        history.remove(index);

                    history.add(bar);
                }
                in.close();
            }

            // Get the data for today (to-date) using a different URL at Yahoo!
            //Bar lastbar = history.getLast
            log.debug("Get data for today using a separate URL..."); //$NON-NLS-1$
            StringBuffer url = new StringBuffer(
                    "http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=sl1d1t1c1ohgv&e=.csv"); //$NON-NLS-1$ //$NON-NLS-2$
            log.debug(url);

            HttpMethod method = new GetMethod(url.toString());
            method.setFollowRedirects(true);
            client.executeMethod(method);

            BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            String inputLine = in.readLine();
            log.trace(inputLine);
            String[] item = inputLine.split(","); //$NON-NLS-1$
            item[2] = item[2].replace("\"", ""); //$NON-NLS-1$ //$NON-NLS-2$

            SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy", Locale.US); //$NON-NLS-1$
            Calendar day = Calendar.getInstance();

            // Transfer the data from the string array to the Bar
            day.setTime(df.parse(item[2]));
            Bar bar = new Bar();
            bar.setDate(day.getTime());
            bar.setOpen(Double.parseDouble(item[5]));
            bar.setClose(Double.parseDouble(item[1]));
            bar.setHigh(Double.parseDouble(item[6]));
            bar.setLow(Double.parseDouble(item[7]));
            bar.setVolume(Long.parseLong(item[8]));

            // Remove the old bar, if exists
            int index = history.indexOf(bar.getDate());
            if (index != -1)
                history.remove(index);
            history.add(bar);

            in.close();

        } catch (Exception e) {
            log.error(e, e);
        }

        CorePlugin.getRepository().save(history);
    } else
        log.warn("Intraday data not supported for " + security.getCode() + " - " + security.getDescription()); //$NON-NLS-1$ //$NON-NLS-2$
}