Example usage for java.time Period between

List of usage examples for java.time Period between

Introduction

In this page you can find the example usage for java.time Period between.

Prototype

public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) 

Source Link

Document

Obtains a Period consisting of the number of years, months, and days between two dates.

Usage

From source file:example.complete.Customer.java

public int getAge() {
    return Period.between(birthday, LocalDate.now()).getYears();
}

From source file:agendapoo.View.FrmCadastroAtividade.java

private boolean isOldTime(LocalDate data, LocalTime end) {
    Period p = Period.between(data, LocalDate.now());
    if (p.getDays() > 0)
        return true;
    else if (p.getDays() == 0) {
        return end.isBefore(LocalTime.now());
    }/*from  w w w .j  av  a 2s.  c o  m*/
    return false;
}

From source file:example.app.model.Person.java

@Transient
@SuppressWarnings("all")
public int getAge() {
    LocalDate birthDate = getBirthDate();
    Assert.state(birthDate != null, String.format("birth date of person [%s] is unknown", getName()));
    Period period = Period.between(birthDate, LocalDate.now());
    return period.getYears();
}

From source file:example.app.core.mapping.json.jackson.serialization.JsonToObjectMappingIntegrationTests.java

protected int ageFor(LocalDate birthDate) {
    return Period.between(birthDate, LocalDate.now()).getYears();
}

From source file:com.omertron.slackbot.functions.Meetup.java

/**
 * Format the MeetUp list into a list of Slack Attachments, up to a certain number of days ahead
 *
 * @param daysAhead//w ww .  ja v  a 2 s . c  o m
 * @param detailed
 * @return
 */
public static Map<LocalDateTime, SlackAttachment> getMeetupsDays(int daysAhead, boolean detailed) {
    LocalDate now = LocalDate.now();
    Map<LocalDateTime, SlackAttachment> results = new HashMap<>();

    Period diff;
    for (MeetupDetails md : MEETUPS) {
        // Correct for BST
        LocalDateTime meetTime = md.getMeetupTime().plusHours(1);

        diff = Period.between(now, meetTime.toLocalDate());
        if (diff.getDays() <= daysAhead) {
            LOG.info("Add: Days: {} - {} - {}", diff.getDays(), meetTime.format(DT_FORMAT), md.getName());
            results.put(meetTime, makeSlackAttachment(md, detailed));
        } else {
            LOG.info("Skip: Days: {} - {} - {}", diff.getDays(), meetTime.format(DT_FORMAT), md.getName());
        }
    }

    return results;
}

From source file:agendapoo.Model.Atividade.java

@Override
public int compareTo(Atividade o) {
    Period p = Period.between(o.data, data);
    if (p.getDays() == 0)
        return this.horaInicio.compareTo(o.getHoraInicio());
    return p.getDays();
}

From source file:br.ufac.sion.dao.InscricaoFacade.java

@Override
public Map<Date, Long> inscricoesPorData(Concurso concurso, SituacaoInscricao situacao) {
    Session session = em.unwrap(Session.class);
    Criteria criteria = session.createCriteria(Inscricao.class);

    LocalDateTime dataInicial = concurso.getDataInicioInscricao();

    Integer dias = Period.between(concurso.getDataInicioInscricao().toLocalDate(),
            concurso.getDataTerminoIncricao().toLocalDate()).getDays();
    Map<Date, Long> resultado = criaMapaVazio(dias, dataInicial);

    criteria.createAlias("cargoConcurso", "cc")
            .setProjection(Projections.projectionList()
                    .add(Projections.sqlGroupProjection("date(data_inscricao) as data", "date(data_inscricao)",
                            new String[] { "data" }, new Type[] { StandardBasicTypes.DATE }))
                    .add(Projections.count("id").as("quantidade")))
            .add(Restrictions.ge("dataInscricao", dataInicial)).add(Restrictions.eq("cc.concurso", concurso));

    if (situacao != null) {
        criteria.add(Restrictions.eq("status", situacao.CONFIRMADA));
    }//from  w  w w .  j a  va2s.c om

    List<DataQuantidade> quantidadesPorData = criteria
            .setResultTransformer(Transformers.aliasToBean(DataQuantidade.class)).list();

    for (DataQuantidade quantidadeData : quantidadesPorData) {
        resultado.put(quantidadeData.getData(), quantidadeData.getQuantidade());
    }

    return resultado;
}

From source file:agendapoo.Control.ControlAtividade.java

/**
 * Verifica se o horrio inserido aps uma atualizao  vlido, ou seja, se entra em conflito
 * com outras atividades, caso entre em conflito com outras atividades retornar False, caso contrrio,
 * True, Como  uma atualizao nesse mtodo a verificao ignorar o horrio que tiver no banco dessa mesma atividade.
 * @param current - Atividade que foi atualizada e que ter seu horrio verificado.
 * @return - valor booleano indicando se o horrio  vlido ou no.
 * @throws SQLException//  ww  w. j  a  v  a2s. c o m
 * @throws IOException
 * @throws ClassNotFoundException 
 */
private boolean isValidTimeUpdate(Atividade current) throws SQLException, IOException, ClassNotFoundException {
    boolean isValid = false;
    List<Atividade> atividades = dao.list(current.getUsuario());
    List<Atividade> sameDay = new ArrayList<>();
    LocalTime start = current.getHoraInicio();
    LocalTime end = current.getHoraFim();

    atividades.stream().forEach((a) -> {
        Period p = Period.between(a.getData(), current.getData());
        if ((p.getDays() == 0) && (!a.getId().equals(current.getId()))) {
            sameDay.add(a);
        }
    });

    if (!sameDay.isEmpty()) {
        for (Atividade a : sameDay)
            if ((start.isBefore(a.getHoraInicio()) && end.isBefore(a.getHoraInicio()))
                    || (start.isAfter(a.getHoraFim()) && end.isAfter(a.getHoraFim())))
                isValid = true;
            else {
                isValid = false;
                break;
            }
        return isValid;
    }
    return true;
}

From source file:ca.phon.session.io.xml.v12.XMLSessionReader_v12.java

private Participant copyParticipant(SessionFactory factory, ParticipantType pt, LocalDate sessionDate) {
    final Participant retVal = factory.createParticipant();

    retVal.setId(pt.getId());/*  w w w  .  ja  v a2  s .c o m*/
    retVal.setName(pt.getName());

    final XMLGregorianCalendar bday = pt.getBirthday();
    if (bday != null) {
        final LocalDate bdt = LocalDate.of(bday.getYear(), bday.getMonth(), bday.getDay());
        retVal.setBirthDate(bdt);

        // calculate age up to the session date
        final Period period = Period.between(bdt, sessionDate);
        retVal.setAgeTo(period);
    }

    final Duration ageDuration = pt.getAge();
    if (ageDuration != null) {
        // convert to period
        final Period age = Period.of(ageDuration.getYears(), ageDuration.getMonths(), ageDuration.getDays());
        retVal.setAge(age);
    }

    retVal.setEducation(pt.getEducation());
    retVal.setGroup(pt.getGroup());

    String langs = "";
    for (String lang : pt.getLanguage())
        langs += (langs.length() > 0 ? ", " : "") + lang;
    retVal.setLanguage(langs);

    if (pt.getSex() == SexType.MALE)
        retVal.setSex(Sex.MALE);
    else if (pt.getSex() == SexType.FEMALE)
        retVal.setSex(Sex.FEMALE);
    else
        retVal.setSex(Sex.UNSPECIFIED);

    ParticipantRole prole = ParticipantRole.fromString(pt.getRole());
    if (prole == null)
        prole = ParticipantRole.TARGET_CHILD;
    retVal.setRole(prole);

    retVal.setSES(pt.getSES());

    return retVal;
}

From source file:edu.lternet.pasta.portal.search.TemporalList.java

private static int calculateMonths(String beginDate, String endDate) {
    int durationInMonths;

    LocalDate localBeginDate = LocalDate.parse(beginDate);
    LocalDate localEndDate = LocalDate.parse(endDate);

    Period duration = Period.between(localBeginDate, localEndDate);
    int years = duration.getYears();
    int months = duration.getMonths();
    int days = duration.getDays();
    durationInMonths = ((years * 12) + months);
    if (days > 15) {
        durationInMonths++;/*from w  w  w . ja v a2s. com*/
    }

    System.out.printf("Begin Date: %s,  End Date: %s\n", beginDate, endDate);
    System.out.printf("The duration is %d years, %d months and %d days\n", duration.getYears(),
            duration.getMonths(), duration.getDays());
    System.out.printf("The total duration in months is %d\n\n", durationInMonths);

    return durationInMonths;
}