Example usage for org.joda.time Period getMinutes

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

Introduction

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

Prototype

public int getMinutes() 

Source Link

Document

Gets the minutes field part of the period.

Usage

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/* w  ww  .java 2  s  . c  o  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 w w . j av a  2  s .  c o m
    return dt.millisOfSecond().roundCeilingCopy().minusMillis(dt.getMillisOfSecond() % p.getMillis());
}

From source file:com.spotify.helios.cli.Output.java

License:Apache License

public static String humanDuration(final Duration dur) {
    final Period p = dur.toPeriod().normalizedStandard();

    if (dur.getStandardSeconds() == 0) {
        return "0 seconds";
    } else if (dur.getStandardSeconds() < 60) {
        return format("%d second%s", p.getSeconds(), p.getSeconds() > 1 ? "s" : "");
    } else if (dur.getStandardMinutes() < 60) {
        return format("%d minute%s", p.getMinutes(), p.getMinutes() > 1 ? "s" : "");
    } else if (dur.getStandardHours() < 24) {
        return format("%d hour%s", p.getHours(), p.getHours() > 1 ? "s" : "");
    } else {//from w  ww .  j  av a2 s  .  c  o  m
        return format("%d day%s", dur.getStandardDays(), dur.getStandardDays() > 1 ? "s" : "");
    }
}

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

License:Apache License

private static String getMinutesCron(Period p) {
    Integer min = p.getMinutes();
    Minutes m = p.toStandardMinutes();//from   ww  w  .  j av  a  2  s.co m
    Integer minutes = m.getMinutes();
    String str = "0" + (min > 0 ? "/" + min : "");
    if (minutes > 60) {
        str = min + "";
    }
    return str;
}

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

License:Open Source License

/**
 * @param args//  w w w .  j a  v  a  2  s .  co  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);
    }
}

From source file:elw.web.FormatTool.java

License:Open Source License

public String formatDuration(final long timeMillis) {
    final Period period = new Period();
    final Period periodNorm = period.plusMillis((int) Math.abs(timeMillis)).normalizedStandard();

    if (periodNorm.getYears() > 0) {
        return lookupPeriodFormatter("y").print(periodNorm);
    } else if (periodNorm.getMonths() > 0) {
        return lookupPeriodFormatter("M").print(periodNorm);
    } else if (periodNorm.getDays() > 0) {
        return lookupPeriodFormatter("d").print(periodNorm);
    } else if (periodNorm.getHours() > 0) {
        return lookupPeriodFormatter("H").print(periodNorm);
    } else if (periodNorm.getMinutes() > 0) {
        return lookupPeriodFormatter("m").print(periodNorm);
    } else {/*  w ww  .  j ava 2  s . c om*/
        //  LATER sometimes durations less than one second occur
        return lookupPeriodFormatter("s").print(periodNorm);
    }
}

From source file:energy.usef.core.service.validation.CorePlanboardValidatorService.java

License:Apache License

/**
 * Validates the PTU Duration against the configured PTU Duration.
 *
 * @param ptuDuration//from  w ww  . j  a v  a2 s  .c o m
 * @throws BusinessValidationException
 */
public void validatePTUDuration(Period ptuDuration) throws BusinessValidationException {
    if (!config.getIntegerProperty(ConfigParam.PTU_DURATION).equals(ptuDuration.getMinutes())) {
        throw new BusinessValidationException(CoreBusinessError.INVALID_PTU_DURATION);
    }
}

From source file:eu.vranckaert.worktime.activities.reporting.ReportingExportActivity.java

License:Apache License

/**
 * Create a {@link Date} instance based on a calculated {@link Period} (aka time-duration) that Excel can handle to
 * display a date.<br/>//from w w  w  . j  ava 2s .com
 * Basically this means that a {@link Date} will be generated for time zone GMT+0 and the default date will be:
 * <b>31/11/1899 00:00:00,00000</b>. To this date the hours, minutes and seconds of the {@link Period} will be
 * added.
 *
 * @param period The period (or time duration) that will need to be converted to an Excel date.
 * @return The Excel date that will be x hours, x minutes and x seconds after 31/11/1899 00:00:00,00000.
 */
private Date getExcelTimeFromPeriod(Period period) {
    Log.d(getApplicationContext(), LOG_TAG, "Creating excel calendar date-time for period " + period);

    /*
     * Specifying the GMT+0 time zone for the Excel calendar fixes the issue that for each excel time displayed a
     * certain amount of hours (always the same amount of hours for all the calculated excel times) is missing.
     * The reason for this is that the Calendar takes the device default time zone (for the emulator being GMT+0 by
     * default). For your own device that could be GMT+01:00. However Excel only works with GMT+0 time zones, if
     * that's not the case it translates the time to the GMT+0 time zone and you loose one hour for every generated
     * Excel time.
     */
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+00:00"));
    cal.set(Calendar.YEAR, 1899);
    cal.set(Calendar.MONTH, 11);
    cal.set(Calendar.DAY_OF_MONTH, 31);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    //cal.add(Calendar.HOUR, -36);

    Log.d(getApplicationContext(), LOG_TAG, "Default excel calendar before adding time: " + cal.getTime());

    int hours = period.getHours();
    int minutes = period.getMinutes();
    int seconds = period.getSeconds();

    if (hours > 0) {
        Log.d(getApplicationContext(), LOG_TAG, "About to add hours to the excel calendar...");
        cal.add(Calendar.HOUR, hours);
        Log.d(getApplicationContext(), LOG_TAG, "Default excel calendar after adding hours: " + cal.getTime());
    }
    if (minutes > 0) {
        Log.d(getApplicationContext(), LOG_TAG, "About to add minutes to the excel calendar...");
        cal.set(Calendar.MINUTE, minutes);
        Log.d(getApplicationContext(), LOG_TAG,
                "Default excel calendar after adding minutes: " + cal.getTime());
    }
    if (seconds > 0) {
        Log.d(getApplicationContext(), LOG_TAG, "About to add seconds to the excel calendar...");
        cal.set(Calendar.SECOND, seconds);
        Log.d(getApplicationContext(), LOG_TAG,
                "Default excel calendar after adding seconds: " + cal.getTime());
    }

    return cal.getTime();
}

From source file:factory.utils.Utils.java

public static String getHoursBetweenDays(Date startDate, Date endDate) throws Exception {

    if (startDate == null) {

        startDate = endDate;/*from  ww  w  . jav a  2  s.c  o  m*/
    }

    DateTime dt1 = new DateTime(startDate.getTime());
    DateTime dt2 = new DateTime(endDate.getTime());

    Period p = new Period(dt1, dt2);
    long hours = p.getDays() * 24 + p.getHours();
    long minutes = p.getMinutes();

    String format = String.format("%%0%dd", 2);

    return String.format(format, hours) + ":" + String.format(format, minutes);
}

From source file:gov.nih.nci.cadsr.cadsrpasswordchange.core.MainServlet.java

License:BSD License

/**
 * Method to detect/handle account lock condition.
 * /*from   w  w  w.j  av  a 2  s  . co m*/
 * @param username
 * @param password
 * @param session
 * @param req
 * @param resp
 * @param redictedUrl
 * @return account status
 * @throws Exception
 */
private String doValidateAccountStatus(String username, HttpSession session, HttpServletRequest req,
        HttpServletResponse resp, String redictedUrl) throws Exception {
    String retVal = "";
    logger.debug("doValidateAccountStatus: entered");

    //check locked state here
    String action = (String) session.getAttribute(Constants.ACTION_TOKEN);
    if (action != null && !action.equals(Constants.UNLOCK_TOKEN)) {
        //CADSRPASSW-29
        connect();
        PasswordChangeDAO dao = new PasswordChangeDAO(datasource);
        List arr = dao.getAccountStatus(username);
        if (arr == null || arr.size() != 2) {
            throw new Exception("Not able to check account status.");
        }
        retVal = (String) arr.get(PasswordChangeDAO.ACCOUNT_STATUS);

        //begin CADSRPASSW-55 - unlock manually as the "password_lock_time 60/1440" does not work
        //         String status = (String)arr.get(PasswordChangeDAO.ACCOUNT_STATUS);
        Date lockedDate = (Date) arr.get(PasswordChangeDAO.LOCK_DATE);
        logger.debug("LockedDate [" + lockedDate + "] Status [" + retVal + "]");
        Period period = null;
        boolean doUnlock = false;
        if (lockedDate != null && retVal != null && retVal.indexOf(Constants.LOCKED_STATUS) > -1) {
            DateTime now = new DateTime();
            period = new Period(new DateTime(lockedDate), now);
            if (period.getHours() >= 1) {
                doUnlock = true;
            }
        }

        if (doUnlock) {
            connect();
            PasswordChangeDAO dao1 = new PasswordChangeDAO(datasource);
            dao1.unlockAccount(username);
            logger.info("Over 1 hour, password lock release (" + period.getMinutes() + " minutes has passed).");
            //logger.debug("Getting the account status again ...");
            //retVal = (String)arr.get(PasswordChangeDAO.ACCOUNT_STATUS);
            retVal = Constants.OPEN_STATUS;
            logger.debug("Account status is [" + retVal + "] now");
        }
        //end CADSRPASSW-55 - unlock manually as the "password_lock_time 60/1440" does not work
        else if (retVal != null && retVal.indexOf(Constants.LOCKED_STATUS) > -1) {
            String tmp = "NOT ABLE TO CALCULATE PERIOD DUE to NULL LOCKED_DATE";
            if (period != null) {
                tmp = String.valueOf(period.getMinutes()) + " minutes has passed).";
            }
            logger.info("Less than 1 hour, password lock stays (" + tmp + ")"); //CADSRPASSW-87
            session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE,
                    Messages.getString("PasswordChangeHelper.103"));
            logger.debug("Redirecting to '" + redictedUrl + "'");
            resp.sendRedirect(redictedUrl);
        }
    }

    logger.debug("doValidateAccountStatus: exiting with retVal [" + retVal + "] ...");

    return retVal;
}