Example usage for org.joda.time Period getDays

List of usage examples for org.joda.time Period getDays

Introduction

In this page you can find the example usage for org.joda.time Period getDays.

Prototype

public int getDays() 

Source Link

Document

Gets the days field part of the period.

Usage

From source file:com.ning.billing.jaxrs.json.OverdueStateJson.java

License:Apache License

public OverdueStateJson(final OverdueState overdueState) {
    this.name = overdueState.getName();
    this.externalMessage = overdueState.getExternalMessage();
    this.daysBetweenPaymentRetries = overdueState.getDaysBetweenPaymentRetries();
    this.disableEntitlementAndChangesBlocked = overdueState.disableEntitlementAndChangesBlocked();
    this.blockChanges = overdueState.blockChanges();
    this.isClearState = overdueState.isClearState();

    Period reevaluationIntervalPeriod = null;
    try {/*from   w ww  .j a  va  2s.  co  m*/
        reevaluationIntervalPeriod = overdueState.getReevaluationInterval();
    } catch (OverdueApiException ignored) {
    }

    if (reevaluationIntervalPeriod != null) {
        this.reevaluationIntervalDays = reevaluationIntervalPeriod.getDays();
    } else {
        this.reevaluationIntervalDays = null;
    }
}

From source file:com.okmich.hackerday.client.tool.dashboard.UserByPeriodHandler.java

private void increasePoints(long mints, long maxts) {

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(mints);//from   w  ww .  j av  a2s . c  o  m

    Calendar cal2 = Calendar.getInstance();
    cal.setTimeInMillis(maxts);

    Period period = new Period(LocalDate.fromCalendarFields(cal), LocalDate.fromCalendarFields(cal2));

    if (period.getDays() <= 7) {
        increasePointValue(ITEM1);
    } else if (period.getMonths() <= 1) {
        increasePointValue(ITEM2);
    } else if (period.getYears() <= 1) {
        increasePointValue(ITEM3);
    } else {
        increasePointValue(ITEM4);
    }
}

From source file:com.reclabs.recomendar.common.helpers.types.DateHelper.java

License:Open Source License

/**
 * Dada una fecha de referencia y una fecha a comparar obtenemos la diferencia de la primera con la segunda, el
 * formato depender del rango de la diferencia, es decir, si hay menos de
 * un mes de diferencia obtendremos la diferencia en das.
 * @param referenceDate The date of reference
 * @param compareDate The date to compare
 * @return Diferencia entre las fechas/*from  w w w.  j  a  va  2s.co m*/
 */
public static String getDifToCompareDateInUnitTimeLowRound(final Date referenceDate, final Date compareDate) {
    Period period = new Period(compareDate.getTime(), referenceDate.getTime(),
            PeriodType.yearMonthDayTime().withSecondsRemoved().withMillisRemoved());
    if ((period.getYears() > 0) || (period.getMonths() > 0) || (period.getDays() > 0)) {
        return REDUCED_DATE_FORMAT.format(compareDate);
    } else if (period.getHours() > 0) {
        return period.getHours() + " Hora" + (period.getHours() > 1 ? "s" : "");
    } else if (period.getMinutes() > 0) {
        return period.getMinutes() + " Minuto" + (period.getMinutes() > 1 ? "s" : "");
    } else {
        return "Ahora";
    }
}

From source file:com.sap.dirigible.runtime.metrics.TimeUtils.java

License:Open Source License

private static DateTime dateTimeCeiling(DateTime dt, Period p) {
    if (p.getYears() != 0) {
        return dt.yearOfEra().roundCeilingCopy().minusYears(dt.getYearOfEra() % p.getYears());
    } else if (p.getMonths() != 0) {
        return dt.monthOfYear().roundCeilingCopy().minusMonths((dt.getMonthOfYear() - 1) % p.getMonths());
    } else if (p.getWeeks() != 0) {
        return dt.weekOfWeekyear().roundCeilingCopy().minusWeeks((dt.getWeekOfWeekyear() - 1) % p.getWeeks());
    } else if (p.getDays() != 0) {
        return dt.dayOfMonth().roundCeilingCopy().minusDays((dt.getDayOfMonth() - 1) % p.getDays());
    } else if (p.getHours() != 0) {
        return dt.hourOfDay().roundCeilingCopy().minusHours(dt.getHourOfDay() % p.getHours());
    } else if (p.getMinutes() != 0) {
        return dt.minuteOfHour().roundCeilingCopy().minusMinutes(dt.getMinuteOfHour() % p.getMinutes());
    } else if (p.getSeconds() != 0) {
        return dt.secondOfMinute().roundCeilingCopy().minusSeconds(dt.getSecondOfMinute() % p.getSeconds());
    }//w  ww  .j av  a2 s .  c o  m
    return dt.millisOfSecond().roundCeilingCopy().minusMillis(dt.getMillisOfSecond() % p.getMillis());
}

From source file:com.squid.kraken.v4.core.analysis.engine.processor.AnalysisCompute.java

License:Open Source License

private IntervalleObject alignPastInterval(IntervalleObject presentInterval, IntervalleObject pastInterval,
        Axis joinAxis) throws ScopeException {

    if (joinAxis != null && presentInterval != null && pastInterval != null) {

        Object lowerPresent = presentInterval.getLowerBound();
        Object lowerPast = pastInterval.getLowerBound();
        Object upperPresent = presentInterval.getUpperBound();
        Object upperPast = pastInterval.getUpperBound();
        ////from  w w  w  .  j a  va  2s .co  m
        IDomain image = joinAxis.getDefinition().getImageDomain();
        if (lowerPresent instanceof Date && lowerPast instanceof Date) {

            DateTime lowerPastDT = new DateTime((Date) lowerPast);
            DateTime lowerPresentDT = new DateTime((Date) lowerPresent);
            DateTime upperPresentDT = new DateTime((Date) upperPresent);
            DateTime upperPastDT = new DateTime((Date) upperPast);

            // realign
            if (image.isInstanceOf(IDomain.YEARLY)) {
                // check if present is an exact number of years
                if (lowerPresentDT.getDayOfYear() == 1
                        && upperPresentDT.getDayOfYear() == upperPresentDT.dayOfYear().getMaximumValue()) {
                    // check of both periods have the same number of days
                    Period presentPeriod = new Period(new LocalDate(lowerPresent),
                            (new LocalDate(upperPresent)), PeriodType.days());
                    Period pastPeriod = new Period(new LocalDate(lowerPast), (new LocalDate(upperPast)),
                            PeriodType.days());
                    if (presentPeriod.getDays() == pastPeriod.getDays()) {
                        presentPeriod = new Period(new LocalDate(lowerPresent),
                                (new LocalDate(upperPresent)).plusDays(1), PeriodType.years());
                        pastPeriod = new Period(new LocalDate(lowerPast),
                                (new LocalDate(upperPast)).plusDays(1), PeriodType.years());

                        // realign
                        if (presentPeriod.getYears() > pastPeriod.getYears()) {
                            // some days are missing to align the periods
                            if (lowerPastDT.getDayOfYear() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(upperPastDT.getYear(), 1, 1, 0, 0).toDate();
                                return new IntervalleObject(newLowerPast, upperPast);
                            }
                            if (upperPastDT.getDayOfYear() != upperPastDT.dayOfYear().getMaximumValue()) {
                                // year over year
                                Date newUpperPast = new DateTime(upperPastDT.getYear(), 12, 31, 23, 59)
                                        .toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);
                            }
                        } else {
                            // either already aligned, or some days should
                            // be removed

                            if (upperPastDT.getDayOfYear() != upperPastDT.dayOfYear().getMaximumValue()) {
                                // year over Year
                                Date newUpperPast = new DateTime(upperPastDT.getYear() - 1, 12, 31, 23, 59)
                                        .toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);

                            }
                            if (lowerPastDT.getDayOfYear() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(lowerPastDT.getYear() + 1, 1, 1, 0, 0)
                                        .toDate();
                                return new IntervalleObject(newLowerPast, upperPast);
                            }

                        }
                    }
                }
            } else if (image.isInstanceOf(IDomain.QUATERLY) || image.isInstanceOf(IDomain.MONTHLY)) {
                // check if present is an exact number of month
                if (lowerPresentDT.getDayOfMonth() == 1
                        && upperPresentDT.getDayOfMonth() == upperPresentDT.dayOfMonth().getMaximumValue()) {
                    // check of both periods have the same number of days
                    Period presentPeriod = new Period(new LocalDate(lowerPresent), new LocalDate(upperPresent),
                            PeriodType.days());
                    Period pastPeriod = new Period(new LocalDate(lowerPast), new LocalDate(upperPast),
                            PeriodType.days());
                    if (presentPeriod.getDays() == pastPeriod.getDays()) {
                        // realign
                        presentPeriod = new Period(new LocalDate(lowerPresent),
                                (new LocalDate(upperPresent)).plusDays(1), PeriodType.months());
                        pastPeriod = new Period(new LocalDate(lowerPast),
                                (new LocalDate(upperPast)).plusDays(1), PeriodType.months());
                        if (presentPeriod.getMonths() > pastPeriod.getMonths()) {
                            // some days are missing

                            if (upperPastDT.getDayOfMonth() != upperPastDT.dayOfMonth().getMaximumValue()) {
                                // month over month
                                Date newUpperPast = new DateTime(upperPastDT.getYear(),
                                        upperPastDT.getMonthOfYear(),
                                        upperPastDT.dayOfMonth().getMaximumValue(), 23, 59).toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);
                            }

                            if (lowerPastDT.getDayOfMonth() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(lowerPastDT.getYear(),
                                        lowerPastDT.getMonthOfYear(), 1, 0, 0).toDate();
                                return new IntervalleObject(newLowerPast, upperPast);

                            }

                        } else {
                            // either already aligned, of some days should
                            // be removed
                            if (upperPastDT.getDayOfMonth() != upperPastDT.dayOfMonth().getMaximumValue()) {
                                /// month over month
                                if (upperPastDT.getMonthOfYear() == 1) {
                                    Date newUpperPast = new DateTime(upperPastDT.getYear() - 1, 12, 31, 23, 59)
                                            .toDate();
                                    return new IntervalleObject(lowerPast, newUpperPast);

                                } else {

                                    upperPastDT = upperPastDT.minusMonths(1);
                                    Date newUpperPast = new DateTime(upperPastDT.getYear(),
                                            upperPastDT.getMonthOfYear(),
                                            upperPastDT.dayOfMonth().getMaximumValue(), 23, 59).toDate();
                                    return new IntervalleObject(lowerPast, newUpperPast);
                                }
                            }
                            if (lowerPastDT.getDayOfMonth() != 1) {
                                // previous period
                                if (lowerPastDT.getMonthOfYear() == 12) {
                                    Date newLowerPast = new DateTime(lowerPastDT.getYear() + 1, 1, 1, 0, 0)
                                            .toDate();
                                    return new IntervalleObject(newLowerPast, upperPast);

                                } else {
                                    lowerPastDT = lowerPastDT.plusMonths(1);
                                    Date newLowerPast = new DateTime(lowerPastDT.getYear(),
                                            lowerPastDT.getMonthOfYear(), 1, 0, 0).toDate();
                                    return new IntervalleObject(newLowerPast, upperPast);

                                }

                            }

                        }
                    }
                }
            }
        }
    }
    return pastInterval;
}

From source file:com.thinkbiganalytics.scheduler.util.TimerToCronExpression.java

License:Apache License

private static String getDaysCron(Period p) {
    Integer days = p.getDays();
    String str = "1" + (days > 0 ? "/" + days : "/1");
    return str;/*w  ww. j a v a  2 s.c  o m*/
}

From source file:com.twigasoft.settings.ClockInOut.java

public boolean checkClockInstance(String type, String status) {
    Connection conn = null;/*  ww  w  .  ja  v a2s . c  o  m*/
    PreparedStatement pst = null;
    ResultSet rs = null;
    String sql = "SELECT create_time FROM tbl_clocking WHERE emp_id=? AND type=? AND status=?";
    Timestamp stamp = null;
    try {
        conn = Database.getConnection();
        pst = conn.prepareStatement(sql);
        pst.setInt(1, app.getEmpId());
        pst.setString(2, type);
        pst.setString(3, status);
        rs = pst.executeQuery();
        while (rs.next()) {
            stamp = rs.getTimestamp(1);
            DateTime timestamp = new DateTime(new Date(stamp.getTime()));
            DateTime now = new DateTime(new Date().getTime());
            Period period = new Period(timestamp, now);
            if (period.getDays() == 0) {
                return true;
            }
        }

    } catch (SQLException ex) {
        ex.printStackTrace();
    } finally {
        try {
            rs.close();
            pst.close();
            conn.close();

        } catch (SQLException ex) {
            Logger.getLogger(ClockInOut.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return false;
}

From source file:control.ConfigController.java

public static boolean doDailyBackup() {
    cdao = new ConfigDAO();
    if (cdao.isSetAutoBackup()) {
        dao = new GenericDAO();
        String s = dao.get("app_config", "last_backup");
        LocalDateTime hoje = new LocalDateTime(System.currentTimeMillis());
        LocalDateTime last_bkp = new LocalDateTime(s);
        Period p = new Period(hoje, last_bkp);
        if ((p.getDays() < 0) || (s == null)) {
            java.io.File file = new java.io.File(
                    System.getProperty("user.home") + System.getProperty("file.separator") + ".jbiblioteca"
                            + System.getProperty("file.separator") + "jbiblioteca_bkp.db");
            try {
                Database.backupDatabase(file);
                ConfigController.saveLastBackupDate("'" + hoje.toString() + "'");
                System.out.println("Backup \"" + file.getCanonicalPath() + "\" salvo. ");
            } catch (Exception ex) {
                Logger.getLogger(ConfigController.class.getName()).log(Level.SEVERE, null, ex);
            }// ww  w  .jav a  2  s .  co  m
            return true;
        }
    }
    return false;
}

From source file:control.EmprestimoController.java

private static TableModel UpdateTablemodel(TableModel tb) {
    LocalDateTime hoje = new LocalDateTime(System.currentTimeMillis());
    for (int i = 0; i < tb.getRowCount(); i++) {
        String in = tb.getValueAt(i, 3).toString();
        String out = tb.getValueAt(i, 4).toString();
        LocalDateTime inicio = new LocalDateTime(in);
        LocalDateTime fim = new LocalDateTime(out);
        tb.setValueAt("" + inicio.getDayOfMonth() + "/" + inicio.getMonthOfYear() + "/" + inicio.getYear() + "",
                i, 3);// w w  w  .ja  v a  2 s  .c om
        tb.setValueAt("" + fim.getDayOfMonth() + "/" + fim.getMonthOfYear() + "/" + fim.getYear() + "", i, 4);

        Period p = new Period(hoje, fim);
        int dias = p.getDays();
        int horas = p.getHours();
        int month = p.getMonths();
        //System.out.println(dias+":"+horas+" :: ENTRE AS DATAS "+fim.toString()+" :: "+hoje.toString());
        if (dias < 1) {
            if (dias == 0) {
                tb.setValueAt("Atraso " + horas * -1 + "h", i, 5);
                if (horas > 0)
                    tb.setValueAt("Restam " + horas + "h", i, 5);
            } else
                tb.setValueAt("Atraso " + dias * -1 + "d:" + horas * -1 + "h", i, 5);

        }
        /*else 
        if (month >= 0)
            tb.setValueAt("Restam "+dias+"d:"+horas+"h", i, 5); 
        else
            tb.setValueAt("Restam "+month+" meses", i, 5); */
    }
    return tb;
}

From source file:edu.jhu.hlt.concrete.stanford.Runner.java

License:Open Source License

/**
 * @param args/* w  ww .j  a  v  a  2s.c o m*/
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler());

    Runner run = new Runner();
    JCommander jc = new JCommander(run, args);
    jc.setProgramName(Runner.class.getName());
    if (run.help) {
        jc.usage();
        System.exit(0);
    }

    int nDocsSeen = 0;
    int nDocsFailed = 0;
    List<String> exIds = new ArrayList<>();
    boolean haveSeenException = false;

    Path outF = Paths.get(run.outputPath);
    Path inp = Paths.get(run.inputPath);
    LOGGER.info("Input path: {}", inp.toString());
    LOGGER.info("Output folder: {}", outF.toString());

    try {
        new ExistingNonDirectoryFile(inp);
        if (!Files.exists(outF)) {
            LOGGER.info("Creating output directory.");
            Files.createDirectories(outF);
        }

        Path outFile = outF.resolve(run.outputName);
        if (Files.exists(outFile)) {
            if (run.overwrite)
                Files.delete(outFile);
            else {
                LOGGER.info("File exists and overwrite = false. Not continuing.");
                System.exit(1);
            }
        }

        PipelineLanguage lang = PipelineLanguage.getEnumeration(run.lang);
        Analytic<? extends WrappedCommunication> a;
        if (run.isInputTokenized)
            a = new AnnotateTokenizedConcrete(lang);
        else
            a = new AnnotateNonTokenizedConcrete(lang);

        StopWatch sw = new StopWatch();
        sw.start();
        LOGGER.info("Beginning ingest at: {}", new DateTime().toString());
        try (InputStream in = Files.newInputStream(inp);
                OutputStream os = Files.newOutputStream(outFile);
                GzipCompressorOutputStream gout = new GzipCompressorOutputStream(os);
                TarArchiver arch = new TarArchiver(gout);) {
            TarGzArchiveEntryCommunicationIterator iter = new TarGzArchiveEntryCommunicationIterator(in);
            while (iter.hasNext()) {
                Communication c = iter.next();
                nDocsSeen++;
                try {
                    arch.addEntry(new ArchivableCommunication(a.annotate(c).getRoot()));
                } catch (AnalyticException e) {
                    LOGGER.warn("Caught analytic exception on document: " + c.getId());
                    nDocsFailed++;
                    exIds.add(c.getId());
                    haveSeenException = true;
                    if (run.exitOnException)
                        break;
                }
            }
        }

        if (run.exitOnException && haveSeenException)
            System.exit(1);

        sw.stop();
        LOGGER.info("Ingest completed at: {}", new DateTime().toString());
        Duration d = new Duration(sw.getTime());
        Period p = d.toPeriod();
        LOGGER.info("Ingest took {}d{}m{}s.", p.getDays(), p.getMinutes(), p.getSeconds());
        final int seenLessFailed = nDocsSeen - nDocsFailed;
        float ratio = nDocsSeen > 0 ? (float) seenLessFailed / nDocsSeen * 100 : 0;
        LOGGER.info("Converted {}% of documents successfully. [{} / {} total]", ratio, seenLessFailed,
                nDocsSeen);
        if (haveSeenException)
            exIds.forEach(eid -> LOGGER.info("Caught exception on document: {}", eid));
    } catch (IOException | NotFileException e) {
        throw new RuntimeException(e);
    }
}