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:io.github.protino.codewatch.ui.widget.PerformanceBarView.java

License:Apache License

private void calculateChange() {
    if (progress < goal) {
        change = (progress / goal) * 100f;
    } else {/*from  w  w w .j ava  2 s  . com*/
        change = 100f;
    }
    change = Math.round(change * 100) / 100f;
    if (progressBarPaint != null) {
        progressBarPaint.setColor((change == 100f) ? barPositiveColor : barNegativeColor);
    }

    if (progressAsDate && startDate != -1 && deadlineDate != -1) {

        long currentTime = new Date().getTime();

        int totalDays = Days.daysBetween(new DateTime(startDate), new DateTime(deadlineDate)).getDays();

        int daysProgressed;
        if (currentTime > startDate) {
            daysProgressed = Days.daysBetween(new DateTime(startDate), new DateTime(currentTime)).getDays();
            if (daysProgressed < totalDays) {
                change = ((float) daysProgressed / totalDays) * 100f;
            } else {
                change = 100f;
            }
        } else {
            daysProgressed = 0;
            change = 0f;
        }
        remainingDays = totalDays - daysProgressed;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("d MMM", Locale.getDefault());
        date = simpleDateFormat.format(new Date(currentTime));
    }
}

From source file:io.github.protino.codewatch.utils.CacheUtils.java

License:Apache License

/**
 * Updates the number of the days the app was used
 *
 * @param context needed to fetch defaultSharedPreferences
 *//*from w  w w .j  ava 2s .  co m*/
public static void updateAppUsage(Context context) {

    long currentTime = System.currentTimeMillis();

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    long lastUsageTime = sharedPreferences.getLong(PREF_APP_LAST_USAGE, -1);

    if (lastUsageTime == -1) {
        editor.putLong(PREF_APP_LAST_USAGE, currentTime);
        editor.putLong(PREF_START_OF_CONSECUTIVE_DAYS, currentTime);
    } else {
        //First check if it's been more than a day since last usage
        int days = Days.daysBetween(new DateTime(lastUsageTime), new DateTime(currentTime)).getDays();
        if (days > 1) {
            editor.putLong(PREF_START_OF_CONSECUTIVE_DAYS, currentTime);
        }
        editor.putLong(PREF_APP_LAST_USAGE, currentTime);
    }
    editor.apply();
}

From source file:io.github.protino.codewatch.utils.CacheUtils.java

License:Apache License

/**
 * @param context needed to fetch defaultSharedPreferences
 * @return number of days the app was opened consecutively
 *///w  w  w .j  a  va  2  s.  c  om
public static int getConsecutiveDays(Context context) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    long lastConsecutiveUsageTime = sharedPreferences.getLong(PREF_START_OF_CONSECUTIVE_DAYS, -1);
    return lastConsecutiveUsageTime == -1 ? 0
            : Days.daysBetween(new DateTime(lastConsecutiveUsageTime), new DateTime(System.currentTimeMillis()))
                    .getDays();
}

From source file:io.macgyver.core.util.CertChecker.java

License:Apache License

protected ObjectNode checkCertificates(ObjectNode nx, List<X509Certificate> certs, String alternateHost) {
    int fewestDaysToExpiration = Integer.MAX_VALUE;
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode problems = (ArrayNode) nx.get("problems");
    ArrayNode certArray = (ArrayNode) nx.get("certs");

    try {/*from w  ww.ja va  2s .  co m*/

        for (X509Certificate cert : certs) {
            ObjectNode n = mapper.createObjectNode();
            String subjectDN = cert.getSubjectDN().getName();
            n.put("subjectDN", subjectDN);

            n.put("subjectCN", extractCN(cert));
            n.put("version", cert.getVersion());
            n.put("issuerDN", cert.getIssuerDN().getName());
            n.put("notValidAfter", ISODateTimeFormat.dateTime().print(cert.getNotAfter().getTime()));
            n.put("notValidAfterTimestamp", cert.getNotAfter().getTime());
            n.put("notValidBefore", ISODateTimeFormat.dateTime().print(cert.getNotBefore().getTime()));
            n.put("notValidBeforeTimestamp", cert.getNotBefore().getTime());
            n.put("serial", cert.getSerialNumber().toString());
            n.put("isDateValid", true);
            n.put("version", cert.getVersion());
            n.put("type", cert.getType());

            if (System.currentTimeMillis() < cert.getNotBefore().getTime()) {
                problems.add(mapper.createObjectNode().put(DESCRIPTION, "certificate not yet valid").put("type",
                        "error"));

                n.put("isDateValid", false);
            }
            if (System.currentTimeMillis() > cert.getNotAfter().getTime()) {

                problems.add(
                        mapper.createObjectNode().put(DESCRIPTION, "certificate expired").put("type", "error"));

                n.put("isDateValid", false);
            }
            int daysToExpiration = Math.max(0,
                    Days.daysBetween(new DateTime(System.currentTimeMillis()), new DateTime(cert.getNotAfter()))
                            .getDays());
            n.put("daysToExpiration", daysToExpiration);
            fewestDaysToExpiration = Math.min(fewestDaysToExpiration, daysToExpiration);

            certArray.add(n);

            Collection<List<?>> altNames = cert.getSubjectAlternativeNames();
            ArrayNode altNameArray = mapper.createArrayNode();
            n.set("subjectAlternativeNames", altNameArray);
            // http://stackoverflow.com/questions/18775206/extracting-subjectalternativename-from-x509-in-java
            if (altNames != null) {
                for (List altList : altNames) {
                    if (altList.size() == 2) {
                        ObjectNode altData = mapper.createObjectNode();
                        altData.put("type", Integer.parseInt(altList.get(0).toString()));
                        altData.put("value", altList.get(1).toString());

                        altNameArray.add(altData);
                    }
                }
            }

        }

    } catch (Exception e) {
        problems.add(mapper.createObjectNode().put("type", "error").put(DESCRIPTION, e.toString()));
    }

    if (!doesCertificateHostnameMatch(certs, alternateHost)) {
        problems.add(mapper.createObjectNode().put(DESCRIPTION, "host name does not match certificate")
                .put("type", "error"));

    }
    if (fewestDaysToExpiration <= getCertExpirationWarningDays()) {
        problems.add(mapper.createObjectNode()
                .put(DESCRIPTION, "certificate will expire in " + fewestDaysToExpiration + " days")
                .put("type", "warning"));
    }

    nx.put("daysToExpiration", fewestDaysToExpiration);
    return nx;
}

From source file:io.prestosql.operator.scalar.DateTimeFunctions.java

License:Apache License

@Description("current date")
@ScalarFunction/*from   w ww .j a v a2s.  com*/
@SqlType(StandardTypes.DATE)
public static long currentDate(ConnectorSession session) {
    ISOChronology chronology = getChronology(session.getTimeZoneKey());

    // It is ok for this method to use the Object interfaces because it is constant folded during
    // plan optimization
    LocalDate currentDate = new DateTime(session.getStartTime(), chronology).toLocalDate();
    return Days.daysBetween(new LocalDate(1970, 1, 1), currentDate).getDays();
}

From source file:io.viewserver.adapters.csv.CsvRecordWrapper.java

License:Apache License

@Override
public Date getDateTime(String columnName) {
    try {//from  w  ww.  j  av a2  s .c  o  m
        String value = getString(columnName);
        Matcher matcher = datePattern.matcher(value);

        if (matcher.find()) {
            String day = matcher.group(1);
            boolean isNegative = matcher.group(2).equals("-");
            int dayValue = dayStringToInt(day);
            int dayOffset = dayValue == 0 ? 0
                    : Days.daysBetween(startDate, startDate.withDayOfWeek(dayValue)).getDays();

            long millisToAdd = dayOffset * 24 * 60 * 60 * 1000;
            long delta = Long.parseLong(matcher.group(3)) - millisToAdd;

            return startTime.plus(delta * (isNegative ? -1 : 1)).toDate();
        }

        return value.equals("") ? null : dateTimeFormat.get().parse(value);
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:io.viewserver.core.BusinessDayCalculator.java

License:Apache License

public int getBusinessDay(ReadableDateTime start, ReadableDateTime end) {
    DateMidnight startMidnight = new DateMidnight(start);
    DateMidnight endMidnight = new DateMidnight(end);

    int weekdayStart = startMidnight.get(DateTimeFieldType.dayOfWeek());
    int weekdayEnd = endMidnight.get(DateTimeFieldType.dayOfWeek());

    if (weekdayStart == DateTimeConstants.SATURDAY) {
        startMidnight = startMidnight.plusDays(2);
        weekdayStart = DateTimeConstants.MONDAY;
    } else if (weekdayStart == DateTimeConstants.SUNDAY) {
        startMidnight = startMidnight.plusDays(1);
        weekdayStart = DateTimeConstants.MONDAY;
    }/*from  w  w  w. j  av  a  2s.c o  m*/

    if (weekdayEnd == DateTimeConstants.SATURDAY) {
        endMidnight = endMidnight.minusDays(1);
        weekdayEnd = DateTimeConstants.FRIDAY;
    } else if (weekdayEnd == DateTimeConstants.SUNDAY) {
        endMidnight = endMidnight.minusDays(2);
        weekdayEnd = DateTimeConstants.FRIDAY;
    }
    int days = Days.daysBetween(startMidnight, endMidnight).getDays();

    startMidnight = startMidnight.plusDays(DateTimeConstants.SATURDAY - weekdayStart);
    endMidnight = endMidnight.plusDays(DateTimeConstants.SATURDAY - weekdayEnd);
    int daysBetweenWeekends = (int) ((endMidnight.getMillis() - startMidnight.getMillis())
            / (24 * 60 * 60 * 1000));
    int weekendDays = daysBetweenWeekends * 2 / 7;
    days -= weekendDays;

    return days;
}

From source file:io.viewserver.expression.function.DateToDay.java

License:Apache License

@Override
public int getInt(int row) {
    return Days.daysBetween(new DateTime(dateExpression.getLong(row), DateTimeZone.UTC),
            DateTime.now(DateTimeZone.UTC)).getDays();
}

From source file:isjexecact.br.com.inso.utils.Funcoes.java

/**
 * Calcula a diferena entre duas datas, retornando o resultado em dias.
 * Caso algum parmetro seja passado como null, retorna -999.
 * @param data1 Primeira data a ser analisada.
 * @param data2 Segunda data a ser analisada.
 * @return Quantidade de dias resultado da diferena entre data1 e data2
 *//*  w w  w  . ja va 2s.  c om*/
public static int calcularDiferencaDataemDias(Date data1, Date data2) {

    if (data1 == null || data2 == null) {
        return -999;
    }

    // Glauber 10/09/2014
    // Estou trabalhando com JodaTime devido a complexidade de se utilizar as classes primitivas do Java, como Date e Calendar

    DateTime datacalc1 = new DateTime(data1);
    DateTime datacalc2 = new DateTime(data2);

    return Days.daysBetween(datacalc1, datacalc2).getDays();

    // Glauber 09/09/2014 - Peguei da net e adaptei pra nossa necessidade
    /*        
             // Criar duas instancias de calendar
            Calendar cal1 = Calendar.getInstance();
            Calendar cal2 = Calendar.getInstance();
                    
            // Set the date for both of the calendar instance
            cal1.set(data1.getYear(), data1.getMonth(), data1.getDay());
            cal2.set(data2.getYear(), data2.getMonth(), data2.getDay());
            
            // Get the represented date in milliseconds
            long milis1 = cal1.getTimeInMillis();
            long milis2 = cal2.getTimeInMillis();
                    
                    
            // Calculate difference in milliseconds
            long diff = milis2 - milis1;
                    
             // Calculate difference in days
            long diffDays = diff / (24 * 60 * 60 * 1000);
            retorno = (int) diffDays;
    */

}

From source file:it.polimi.se.calcare.service.EventFacadeREST.java

private List<Forecast> forecastCreator(Date s, Date e, City city) throws JSONException, IOException {
    DateTime start = new DateTime(s);
    DateTime end = new DateTime(e);
    int cnt = Days.daysBetween(start, end).getDays();
    List<Forecast> toUpdate = new ArrayList<>();

    for (int i = 0; i <= cnt; i++) {
        Forecast forecast = new Forecast(new ForecastPK(start.plusDays(i).toDate(), city.getId()), 0, 0, 0, 0);
        toUpdate.add(forecast);//from   www  . j a  v a2  s .  c om
    }
    List<Forecast> toPush = new GetWeather().updateForecast(city, toUpdate);

    for (Forecast item : toPush) {
        em.merge(item);
    }
    em.flush();
    return toPush;

}