Example usage for org.joda.time Days daysBetween

List of usage examples for org.joda.time Days daysBetween

Introduction

In this page you can find the example usage for org.joda.time Days daysBetween.

Prototype

public static Days daysBetween(ReadablePartial start, ReadablePartial end) 

Source Link

Document

Creates a Days representing the number of whole days between the two specified partial datetimes.

Usage

From source file:ru.caramel.juniperbot.module.social.service.impl.YouTubeServiceImpl.java

License:Open Source License

@Override
@Transactional/*from   w w  w  .ja va2  s. com*/
public void notifyVideo(String channelId, String videoId) {
    synchronized (videoCache) {
        if (videoCache.getIfPresent(videoId) != null) {
            return; // do not notify this video again
        }
        videoCache.put(videoId, videoId);
    }

    try {
        Video video = getVideoById(videoId, "id,snippet");
        if (video == null) {
            log.error("No suitable video found for id={}", videoId);
            return;
        }

        if (video.getSnippet() != null && video.getSnippet().getPublishedAt() != null) {
            var publishedAt = video.getSnippet().getPublishedAt();
            LocalDate dateTime = new DateTime(publishedAt.getValue()).toLocalDate();
            if (Days.daysBetween(dateTime, LocalDate.now()).getDays() >= 1) {
                return;
            }
        }
        repository.findActiveConnections(channelId).forEach(e -> notifyConnection(video, e));
    } catch (Exception e) {
        videoCache.invalidate(videoId);
        throw e;
    }
}

From source file:ru.touchin.templates.calendar.CalendarUtils.java

License:Apache License

/**
 * Create list of {@link CalendarItem} according to start and end Dates.
 *
 * @param startDate Start date of the range;
 * @param endDate   End date of the range;
 * @return List of CalendarItems that could be one of these: {@link CalendarHeaderItem}, {@link CalendarDayItem} or {@link CalendarEmptyItem}.
 *//*from ww  w.ja  va  2  s.  c  o  m*/
@NonNull
@SuppressWarnings("checkstyle:MethodLength")
public static List<CalendarItem> fillRanges(@NonNull final DateTime startDate,
        @NonNull final DateTime endDate) {
    final DateTime cleanStartDate = startDate.withTimeAtStartOfDay();
    final DateTime cleanEndDate = endDate.plusDays(1).withTimeAtStartOfDay();

    DateTime tempTime = cleanStartDate;

    final List<CalendarItem> calendarItems = fillCalendarTillCurrentDate(cleanStartDate, tempTime);

    tempTime = tempTime.plusDays(Days.ONE.getDays());

    final int totalDaysCount = Days.daysBetween(tempTime, cleanEndDate).getDays();
    int shift = calendarItems.get(calendarItems.size() - 1).getEndRange();
    int firstDate = tempTime.getDayOfMonth() - 1;
    int daysEnded = 1;

    while (true) {
        final int daysInCurrentMonth = tempTime.dayOfMonth().getMaximumValue();
        final long firstRangeDate = tempTime.getMillis();

        if ((daysEnded + (daysInCurrentMonth - firstDate)) <= totalDaysCount) {
            tempTime = tempTime.plusMonths(1).withDayOfMonth(1);

            calendarItems.add(new CalendarDayItem(firstRangeDate, firstDate + 1, shift + daysEnded,
                    shift + daysEnded + (daysInCurrentMonth - firstDate) - 1, ComparingToToday.AFTER_TODAY));
            daysEnded += daysInCurrentMonth - firstDate;
            if (daysEnded == totalDaysCount) {
                break;
            }
            firstDate = 0;

            final int firstDayInWeek = tempTime.getDayOfWeek() - 1;

            if (firstDayInWeek != 0) {
                calendarItems.add(new CalendarEmptyItem(shift + daysEnded,
                        shift + daysEnded + (DAYS_IN_WEEK - firstDayInWeek - 1)));
                shift += (DAYS_IN_WEEK - firstDayInWeek);
            }

            calendarItems.add(new CalendarHeaderItem(tempTime.getYear(), tempTime.getMonthOfYear() - 1,
                    shift + daysEnded, shift + daysEnded));
            shift += 1;

            if (firstDayInWeek != 0) {
                calendarItems
                        .add(new CalendarEmptyItem(shift + daysEnded, shift + daysEnded + firstDayInWeek - 1));
                shift += firstDayInWeek;
            }

        } else {
            calendarItems.add(new CalendarDayItem(firstRangeDate, firstDate + 1, shift + daysEnded,
                    shift + totalDaysCount, ComparingToToday.AFTER_TODAY));
            break;
        }
    }

    return calendarItems;
}

From source file:se.skl.skltpservices.npoadapter.mapper.MedicationHistoryMapper.java

License:Open Source License

protected PQIntervalType getTreatmentInterval(IVLTS dosageIvlts) {

    PQIntervalType treatmentInterval = null;

    // if width is supplied, use it
    if (dosageIvlts.getWidth() != null) {
        QTY width = dosageIvlts.getWidth();
        if (width instanceof PQTIME) {
            PQTIME pqtimeWidth = (PQTIME) width;
            Double widthValue = pqtimeWidth.getValue();
            if (widthValue != null) {
                if (widthValue >= 0) {
                    if (StringUtils.isNotBlank(pqtimeWidth.getUnit())) {
                        treatmentInterval = new PQIntervalType();
                        treatmentInterval.setLow(widthValue);
                        treatmentInterval.setHigh(widthValue);
                        treatmentInterval.setUnit(pqtimeWidth.getUnit());
                    } else {
                        log.error("lkm-dst-bet value/width/unit missing");
                    }//  w  w  w  .  j av a2s  .co m
                } else {
                    log.error("lkm-dst-bet value/width/value is negative " + widthValue);
                }
            } else {
                log.error("lkm-dst-bet value/width/value null");
            }
        } else {
            log.error("lkm-dst-bet value/width - expecting PQTIME, received " + width.getClass().getName());
        }
    } else if (dosageIvlts.getLow() != null && dosageIvlts.getHigh() != null
            && StringUtils.isNotBlank(dosageIvlts.getLow().getValue())
            && StringUtils.isNotBlank(dosageIvlts.getHigh().getValue())) {

        // there is no width, but there are low and high

        String lowString = dosageIvlts.getLow().getValue();
        String highString = dosageIvlts.getHigh().getValue();
        try {
            DateFormat dateformatTS = new SimpleDateFormat(TIMESTAMPFORMAT);
            Date lowDate = dateformatTS.parse(lowString);
            try {
                Date highDate = dateformatTS.parse(highString);
                if (!lowDate.after(highDate)) {
                    // let joda time do the hard work
                    int days = Days.daysBetween(new DateTime(lowDate), new DateTime(highDate)).getDays();
                    treatmentInterval = new PQIntervalType();
                    treatmentInterval.setLow(new Double(days));
                    treatmentInterval.setHigh(treatmentInterval.getLow());
                    treatmentInterval.setUnit("d");
                } else {
                    log.error("lkm-dst-bet low (" + lowString + ") is after high (" + highString + ")");
                }
            } catch (ParseException p) {
                log.error("lkm-dst-bet value/high invalid timestamp:" + lowString);
            }
        } catch (ParseException p) {
            log.error("lkm-dst-bet value/low invalid timestamp:" + lowString);
        }
    } else {
        // the message does not follow the contract
        // this is the case for data in qa
        log.debug("lkm-dst-bet width is null and both low and high are not present - low:"
                + (dosageIvlts.getLow() == null ? "null" : dosageIvlts.getLow().getValue()) + ", high:"
                + (dosageIvlts.getHigh() == null ? "null" : dosageIvlts.getHigh().getValue()));
    }
    return treatmentInterval;
}

From source file:se3prac8.SE3Prac8.java

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    String line = s.nextLine();/*from w w  w.ja  v a2 s  .  co m*/
    DateTime parsedDate = null;
    // TODO code application logic here
    if (charCheck(line)) {
        if (line.indexOf(".") != -1) {
            parsedDate = parseYFrac(line);
        } else {
            parsedDate = d_wM_y(line);
        }
    } else {
        if (line.length() >= 8) {
            parsedDate = parseYMD(line);
        } else if (line.length() <= 4) {
            System.out.println("IsRunning");
            parsedDate = new DateTime(Integer.parseInt(line), 1, 1, 0, 0);
        } else {
            System.out.println("Error");
        }
    }
    Days days;

    days = Days.daysBetween(unixTime, parsedDate);
    long secondsPassed = days.getDays() * secInDay;

    System.out.println(secondsPassed);
}

From source file:Servlets.chooseCarServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from ww w . java2s  . c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //the loop checks what button you have clicked
    //the name of the button is the same as the car id
    // so that we can get the correct booking info from the database
    for (int i = 0; i < 1000; i++) {
        if (request.getParameter("" + i) != null) {
            System.out.println("the car id you choose: " + i);

            //connects to the database so that we can get the correct information about the car
            HybernateUtil hu = new HybernateUtil();
            SessionFactory sessionFactory = hu.getSessionFactory();

            Session session = sessionFactory.openSession();
            session.beginTransaction();
            Car c = new Car();
            c = (Car) session.get(Car.class, i);
            session.getTransaction().commit();

            //formatting the dates so that we can calculate how many days the client has chosen
            //calculates the totalprice based on the daily price * the days it is going to be rented
            //updates the datastorage
            int price = c.getDailyPrice();
            statefulBean sfb = new statefulBean();
            String pickUpDate = sfb.getPickUpDate();
            String dropOfDate = sfb.getDropOfDate();
            System.out.println(pickUpDate + " " + dropOfDate);
            DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy");
            DateTime first = formatter.parseDateTime(pickUpDate);
            DateTime second = formatter.parseDateTime(dropOfDate);
            int dif = 0;
            dif = Days.daysBetween(first, second).getDays();

            System.out.println(dif);

            price = price * dif;
            System.out.println(price);

            //Updates the datastorage some more and sets the attributes for the next page
            //so that the client knows what he/she is paying for
            statefulBean stb = new statefulBean();
            stb.setCarPrice(price);

            //                request.setAttribute("name", c.getCarName());
            //                request.setAttribute("addres", c.getCarName());
            //                request.setAttribute("phone", c.getCarName());
            //                request.setAttribute("email", c.getCarName());
            request.setAttribute("carName", c.getCarName());
            request.setAttribute("carType", c.getCarType());
            request.setAttribute("carHome", c.getCarHome());
            request.setAttribute("carLocation", c.getCarlocation());
            request.setAttribute("pickUpDate", pickUpDate);
            request.setAttribute("dropOdDate", dropOfDate);
            request.setAttribute("loggedIn", "" + stb.getLoggedIn());

            request.setAttribute("carPrice", price);

            //some more datastorage updates
            sfb.setCarName(c.getCarName());
            sfb.setCarType(c.getCarType());
            sfb.setCarHome(c.getCarHome());
            sfb.setCarId(c.getIdCar());

            request.getRequestDispatcher("confirmPurchase.jsp").forward(request, response);
            break;
        }

    }

    processRequest(request, response);
}

From source file:Servlets.Disponibilidade.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    Usuario user = (Usuario) session.getAttribute("user");
    session.setAttribute("user", session.getAttribute("user"));

    String dtRetirada = request.getParameter("dtRetirada");
    String dtDevolucao = request.getParameter("dtDevolucao");
    String veicEscolhido = request.getParameter("filial");
    System.out.println(veicEscolhido);
    int filial = Integer.parseInt(veicEscolhido);
    Date ret = null;//from  w ww.  j  a  va 2s  .c  o  m
    Date dev = null;
    String dtR = null;
    String dtD = null;
    try {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dfmt = new SimpleDateFormat("dd/MM/yyyy");
        dtR = dfmt.format(sdf1.parse(dtRetirada));
        dtD = dfmt.format(sdf1.parse(dtDevolucao));
        ret = dfmt.parse(dtR);
        dev = dfmt.parse(dtD);

    } catch (Exception e) {
        e.printStackTrace();
    }

    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
    DateTime start = formatter.parseDateTime(dtR);
    //http://johannburkard.de/blog/programming/java/date-time-parsing-formatting-joda-time.html
    DateTime end = formatter.parseDateTime(dtD);
    int dias = Days.daysBetween(start, end).getDays();
    VeiculoDAO vdao = new VeiculoDAO();
    List<Veiculos> listaVeic = vdao.verificarDisponibilidadeByFilial(filial);
    if (ret.after(dev)) {
        request.setAttribute("erroDt", true);
        request.getRequestDispatcher("Contrato_1.jsp").forward(request, response);
    }

    request.setAttribute("ret", ret);
    request.setAttribute("dev", dev);
    request.setAttribute("filial", filial);
    request.setAttribute("diarias", dias);

    if (listaVeic.isEmpty()) {
        request.setAttribute("erro", true);
        request.getRequestDispatcher("Contrato_1.jsp").forward(request, response);
    } else {
        request.setAttribute("veic", listaVeic);
    }
    request.getRequestDispatcher("Contrato_2.jsp").forward(request, response);
}

From source file:supply.CapacityHarvester.java

License:Apache License

public static int getCalculatedRemainingHours(String username) {
    // Find start and end date for current sprint
    // --> Lookup sprint setup

    // Business days To Sprint End
    DateTime sprintStartDate = new DateTime(2014, 02, 1, 0, 0, 0, 0);
    DateTime sprintEndDate = new DateTime(2014, 02, 28, 17, 0);
    logger.info("sprintEndDate WeekOfWeekyear=" + sprintEndDate.getWeekOfWeekyear());
    logger.info("sprintEndDate WeekOfWeekyear=" + sprintEndDate.getWeekOfWeekyear());
    LocalDate today = new LocalDate();

    // business days left in current week
    logger.info("Current week=" + today.getWeekOfWeekyear());
    if (today.getDayOfWeek() > 5) {
        logger.info("Not a business day. 0 hours left of availability as this is weekend.");
    }/* w ww .  j  a  va  2s  .  c  o m*/
    SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy");
    Period weekPeriod = new Period().withWeeks(1);
    Interval i = new Interval(sprintStartDate, weekPeriod);
    int hours = 0;
    while (i.getEnd().isBefore(sprintEndDate)) {
        logger.info("week: " + i.getStart().getWeekOfWeekyear() + " start: " + df.format(i.getStart().toDate())
                + " end: " + df.format(i.getEnd().minusMillis(1).toDate()));
        i = new Interval(i.getStart().plus(weekPeriod), weekPeriod);
        int availabilityHours = Availability.getAvailability(i.getStart().toCalendar(Locale.US), username);
        logger.info("Reported availability hours for [" + username + "]: " + availabilityHours);
        hours += availabilityHours;
    }

    Days days = Days.daysBetween(today.toDateTimeAtStartOfDay(), sprintEndDate);

    int hoursRemaining = Hours.hoursBetween(today.toDateTimeAtCurrentTime(), sprintEndDate).getHours();
    if (hoursRemaining < 0)
        hoursRemaining = 0;
    logger.info("HoursToSprintEnd=" + hoursRemaining);
    logger.info("DayOfWeek=" + today.getDayOfWeek());
    logger.info("WeekOfWeekyear=" + today.getWeekOfWeekyear());
    logger.info("Hours from DB=" + hours);

    // --> Find week numbers
    // --> Check that current date is between start/end date of sprint

    // Lookup how many hours this user has for the sprint
    // --> lookup in HBase
    // --> 

    return hoursRemaining;
}

From source file:task.first.nested.classes.and.enums.CustomeDate.java

public static int daysBetween(Date firstTime, Date secondTime) {
    return Days.daysBetween(new DateTime(firstTime), new DateTime(secondTime)).getDays();
}

From source file:Tools.CrawlersConnector.java

public ArrayList<CustomStatus> readScenario(String scenario)
        throws MalformedURLException, IOException, JSONException {
    //databaseHandler dbh=new databaseHandler();
    BaselineAnalysisTools bat = new BaselineAnalysisTools();
    ArrayList<CustomStatus> res;
    ArrayList<CustomStatus> trueRes = new ArrayList<CustomStatus>();
    ArrayList<String> allkeys = new ArrayList<String>();
    Date now = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(now);/* w w w . j  a v a2 s  .  c om*/
    c.add(Calendar.DATE, dateDiff);
    Date before6months = c.getTime();
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    if (scenario.trim().toLowerCase().equals("transportation")) {
        allkeys.addAll(transportKeywords1);
        allkeys.addAll(transportKeywords2);
        allkeys.addAll(transportKeywords3);
        allkeys.addAll(transportKeywords4);
        allkeys.addAll(transportKeywords5);
        allkeys.addAll(transportKeywords6);
    } else if (scenario.trim().toLowerCase().equals("biofuel")) {
        allkeys.addAll(biofuelKeywords1);
        allkeys.addAll(biofuelKeywords2);
        allkeys.addAll(biofuelKeywords3);
        allkeys.addAll(biofuelKeywords4);
    }
    for (int i = 0; i < allkeys.size(); i++) {
        try {
            before6months = c.getTime();
            System.out.println(allkeys.get(i) + " started.");
            //res=dbh.readTweets(allkeys.get(i),null);
            res = GlobalVarsStore.publicDBh.readTweets(allkeys.get(i), null);
            boolean cancel = false;
            if (res == null) {
                res = new ArrayList<CustomStatus>();
            } else if (res.size() > 0) {
                try {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    before6months = formatter.parse(res.get(0).getCreatedAt());
                    int days = Days.daysBetween(new DateTime(before6months), new DateTime(now)).getDays();
                    if (days > 2) {
                        before6months = c.getTime();
                    } else if (days < 1) {
                        cancel = true;
                        System.out.println(allkeys.get(i) + " canceled.");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    before6months = c.getTime();
                }
            }
            if (!cancel) {
                TwitterCrawler tc = new TwitterCrawler();
                System.out.println(allkeys.get(i) + " -filter:links since:" + sf.format(before6months));
                List<CustomStatus> tweetsCrawled = tc.safeSearch(
                        (allkeys.get(i) + " -filter:links").replace(" ", "%20"), sf.format(before6months));
                for (int j = 0; j < tweetsCrawled.size(); j++) {
                    if (!tweetsCrawled.get(j).getClearText().contains("URL"))
                        res.add(tweetsCrawled.get(j));
                }
                res = clearDuplicateStatuses(res);
                System.out.println("Set cleared.");
                for (int j = 0; j < res.size(); j++) {
                    try {
                        CustomStatus cur = res.get(j);
                        cur.setPolarity(bat.SentiWordNetMeanAnalysisSingle(cur));
                        GlobalVarsStore.publicDBh.insertTweet(cur.getKeyword(), cur.getText(),
                                cur.getPolarity(), cur.getId(), cur.getCreatedAt());
                        trueRes.add(cur);
                    } catch (Exception exe) {
                        exe.printStackTrace();
                    }
                }
            } else {
                trueRes.addAll(res);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    System.out.println("Scenario returned.");
    return trueRes;
}

From source file:Tools.CrawlersConnector.java

public ArrayList<CustomStatus> readObjective(String scenario, int objective)
        throws MalformedURLException, IOException, JSONException, ParseException {
    //databaseHandler dbh=new databaseHandler();
    BaselineAnalysisTools bat = new BaselineAnalysisTools();
    ArrayList<CustomStatus> res;
    TwitterCrawler tc = new TwitterCrawler();
    ArrayList<CustomStatus> trueRes = new ArrayList<CustomStatus>();
    ArrayList<String> allkeys = new ArrayList<String>();
    Date now = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(now);/*from  w ww.j  a  v a  2s  . c  o m*/
    c.add(Calendar.DATE, dateDiff);
    Date before6months = c.getTime();
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    if (scenario.trim().toLowerCase().equals("transportation")) {
        if (objective == 1) {
            allkeys = transportKeywords1;
        } else if (objective == 2) {
            allkeys = transportKeywords2;
        } else if (objective == 3) {
            allkeys = transportKeywords3;
        } else if (objective == 4) {
            allkeys = transportKeywords4;
        } else if (objective == 5) {
            allkeys = transportKeywords5;
        } else if (objective == 6) {
            allkeys = transportKeywords6;
        }
    } else if (scenario.trim().toLowerCase().equals("biofuel")) {
        if (objective == 1) {
            allkeys = biofuelKeywords1;
        } else if (objective == 2) {
            allkeys = biofuelKeywords2;
        } else if (objective == 3) {
            allkeys = biofuelKeywords3;
        } else if (objective == 4) {
            allkeys = biofuelKeywords4;
        }
    }
    for (int i = 0; i < allkeys.size(); i++) {
        before6months = c.getTime();
        res = GlobalVarsStore.publicDBh.readTweets(allkeys.get(i), null);
        boolean cancel = false;
        if (res == null) {
            res = new ArrayList<CustomStatus>();
        } else if (res.size() > 0) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            before6months = formatter.parse(res.get(0).getCreatedAt());
            int days = Days.daysBetween(new DateTime(before6months), new DateTime(now)).getDays();
            if (days > 2) {
                before6months = c.getTime();
            } else if (days < 1)
                cancel = true;
        }
        if (!cancel) {
            System.out.println(allkeys.get(i) + " -filter:links since:" + sf.format(before6months));
            List<CustomStatus> tweetsCrawled = tc.safeSearch(
                    (allkeys.get(i) + " -filter:links").replace(" ", "%20"), sf.format(before6months));
            for (int j = 0; j < tweetsCrawled.size(); j++) {
                if (!tweetsCrawled.get(j).getClearText().contains("URL"))
                    res.add(tweetsCrawled.get(j));
            }
            res = clearDuplicateStatuses(res);
            for (int j = 0; j < res.size(); j++) {
                CustomStatus cur = res.get(j);
                cur.setPolarity(bat.SentiWordNetMeanAnalysisSingle(cur));
                GlobalVarsStore.publicDBh.insertTweet(cur.getKeyword(), cur.getText(), cur.getPolarity(),
                        cur.getId(), cur.getCreatedAt());
                trueRes.add(cur);
            }
        } else {
            trueRes.addAll(res);
        }
    }
    return clearDuplicateStatuses(trueRes);
}