Example usage for java.time LocalDate atStartOfDay

List of usage examples for java.time LocalDate atStartOfDay

Introduction

In this page you can find the example usage for java.time LocalDate atStartOfDay.

Prototype

public ZonedDateTime atStartOfDay(ZoneId zone) 

Source Link

Document

Returns a zoned date-time from this date at the earliest valid time according to the rules in the time-zone.

Usage

From source file:org.ojbc.util.model.rapback.IdentificationResultSearchRequest.java

public void setReportedDateStartLocalDate(LocalDate localDate) {
    this.reportedDateStartDate = localDate == null ? null
            : Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
}

From source file:com.chadekin.jadys.syntax.SqlNativeQuerySectionDetailedITest.java

@Test
public void shouldBuildAllSqlQuerySection() {
    // Arrange/*from w ww  . j a v a2s .c om*/
    Calendar calendar = Calendar.getInstance();
    LocalDate localDate = LocalDate.of(2016, Month.DECEMBER, 14);
    Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    String internalSql = DynamicSqlFactory.newQuery().select("cus.Id_").count("*", "cus.numberOfLocation")
            .from("dct_customer").as("cus").join("dct_location", "loc").on("loc.customerId").equal("cus.id_")
            .where("cus.companyId").equal(142576).and("cus.customerId").equal(1258).and("cus.customerName")
            .like("BSD GmbH").and("zipCode").like(StringUtils.EMPTY).and("cus.city").like("Paris")
            .and("country").like(null).and("cus.externalId").like("456753").and("cus.customerType")
            .like(CustomerType.KEY_ACCOUNT).and("cus.modifiedDate").greaterThanOrEqual("2016-10-14")
            .and("cus.modifiedDate").lessThanOrEqual(date).and("cus.modifiedByUserId")
            .in(Lists.newArrayList(125, 36, 587)).groupBy("loc.customerId").having("COUNT(loc.customerId)")
            .equal(2).orderBy("cus.externalId").asc().build();

    // Act
    String sql = DynamicSqlFactory.newQuery().select().count().from(internalSql).as("subQuery").build();

    // Assert
    assertThatSelect(sql);
    assertThatFrom(sql);
    assertThatJoin(sql);
    assertThatWhere(sql);
    assertThatAnd(sql);
    assertThatGroupBy(sql);
    assertThatHaving(sql);
    assertThatOrderBy(sql);
    assertThatAll(sql);
}

From source file:org.openmrs.module.operationtheater.api.impl.OperationTheaterServiceImpl.java

@Override
public Interval getLocationAvailableTime(Location location, LocalDate date) {
    Date date1 = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
    Date date2 = Date.from(date.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
    List<AppointmentBlock> blocks = appointmentService.getAppointmentBlocks(date1, date2,
            location.getId() + ",", null, null);
    //      List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();

    if (blocks.size() == 1) {
        //         return new Interval(new DateTime(blocks.get(0).getStartDate()), new DateTime(blocks.get(0).getEndDate()));
        Instant startInstant = LocalDateTime.from(blocks.get(0).getStartDate().toInstant())
                .toInstant(ZoneOffset.UTC);
        Instant endInstant = LocalDateTime.from(blocks.get(0).getEndDate().toInstant())
                .toInstant(ZoneOffset.UTC);
        return Interval.of(startInstant, endInstant);
    } else if (blocks.size() > 1) {
        throw new APIException("There shouldn't be multiple appointment blocks per location and date");
    }//from w  w  w .j  ava2s.c  o  m

    DateTimeFormatter timeFormatter = OTMetadata.AVAILABLE_TIME_FORMATTER;
    LocalDateTime availableStart = null;
    LocalDateTime availableEnd = null;
    for (LocationAttribute attribute : location.getAttributes()) {
        if (attribute.getAttributeType().getUuid().equals(OTMetadata.DEFAULT_AVAILABLE_TIME_BEGIN_UUID)) {
            LocalTime beginTime = LocalTime.parse((String) attribute.getValue(), timeFormatter);
            //            availableStart = date.withTime(beginTime.getHourOfDay(), beginTime.getMinuteOfHour(), 0, 0);
            availableStart = date.atTime(beginTime.getHour(), beginTime.getMinute());
        } else if (attribute.getAttributeType().getUuid().equals(OTMetadata.DEFAULT_AVAILABLE_TIME_END_UUID)) {
            LocalTime endTime = LocalTime.parse((String) attribute.getValue(), timeFormatter);
            //            availableEnd = date.withTime(endTime.getHourOfDay(), endTime.getMinuteOfHour(), 0, 0);
            availableEnd = date.atTime(endTime.getHour(), endTime.getMinute());
        }
    }

    if (availableStart != null && availableEnd != null) {
        return Interval.of(availableStart.toInstant(ZoneOffset.UTC), availableEnd.toInstant(ZoneOffset.UTC));
    }

    throw new APIException("Available times not defined. please make sure that the attributes "
            + "'default available time begin' and 'default available time end' for the location "
            + location.getName() + " are defined");

}

From source file:net.ceos.project.poi.annotated.core.CsvHandler.java

/**
 * Apply a date time value at the field.
 * /*from w ww.  j  a  v a  2 s  .co  m*/
 * @param value
 *            the value
 * @param formatMask
 *            the decorator mask
 * @param transformMask
 *            the transformation mask
 * @return false if problem otherwise true
 * @throws ConverterException
 *             the conversion exception type
 */
protected static String toLocalDate(final LocalDate value, final String formatMask, final String transformMask)
        throws ConverterException {
    String dateMasked = StringUtils.EMPTY;
    if (value != null) {
        try {
            if (StringUtils.isNotBlank(transformMask)) {
                // apply transformation mask
                dateMasked = applyMaskToDate(Date.from(value.atStartOfDay(ZoneId.systemDefault()).toInstant()),
                        transformMask);

            } else if (StringUtils.isNotBlank(formatMask)) {
                // apply format mask
                dateMasked = applyMaskToDate(Date.from(value.atStartOfDay(ZoneId.systemDefault()).toInstant()),
                        formatMask);

            } else {
                // default mask
                dateMasked = applyMaskToDate(Date.from(value.atStartOfDay(ZoneId.systemDefault()).toInstant()),
                        Constants.DD_MMM_YYYY_HH_MM_SS);
            }
        } catch (Exception e) {
            throw new ConverterException(ExceptionMessage.CONVERTER_LOCALDATE.getMessage(), e);
        }
    }
    return dateMasked;
}

From source file:currency.converter.openexchangerate.OpenExchangeCurrencyConverter.java

/**
 * Saves currency exchange rate history of the logged in user
 * /* w w  w .  j a va 2s. c  o m*/
 * @param rates Currency rates to be saved
 * @param baseCurrency Base currency which was used in the search
 * @param amount Amount of base currency
 * @param dateOfRate Date when the search was performed
 * @param userName Username of the user who has searched the exchange rate
 * 
 * @throws InvalidParameterException for invalid arguments
 */
private void saveExchangeRate(CurrencyRateModel rates, String baseCurrency, double amount, LocalDate dateOfRate,
        String userName) throws InvalidParameterException {

    Currency currency = getCurrency(baseCurrency);
    Date date = Date.from(dateOfRate.atStartOfDay(ZoneId.systemDefault()).toInstant());

    CurrencyHistory currencyHistory = new CurrencyHistory(currency.getId(), amount, date, userName);
    historyRepository.save(currencyHistory);

    // Save rates
    saveCurrencyRates(currencyHistory, rates, baseCurrency);
}

From source file:cn.afterturn.easypoi.excel.export.base.ExportCommonService.java

private Object dateFormatValue(Object value, ExcelExportEntity entity) throws Exception {
    Date temp = null;/*ww w.ja  va 2s.co  m*/
    if (value instanceof String && StringUtils.isNoneEmpty(value.toString())) {
        SimpleDateFormat format = new SimpleDateFormat(entity.getDatabaseFormat());
        temp = format.parse(value.toString());
    } else if (value instanceof Date) {
        temp = (Date) value;
    } else if (value instanceof Instant) {
        Instant instant = (Instant) value;
        temp = Date.from(instant);
    } else if (value instanceof LocalDate) {
        LocalDate localDate = (LocalDate) value;
        temp = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    } else if (value instanceof LocalDateTime) {
        LocalDateTime localDateTime = (LocalDateTime) value;
        temp = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    } else if (value instanceof java.sql.Date) {
        temp = new Date(((java.sql.Date) value).getTime());
    } else if (value instanceof java.sql.Time) {
        temp = new Date(((java.sql.Time) value).getTime());
    } else if (value instanceof java.sql.Timestamp) {
        temp = new Date(((java.sql.Timestamp) value).getTime());
    }
    if (temp != null) {
        SimpleDateFormat format = new SimpleDateFormat(entity.getFormat());
        if (StringUtils.isNotEmpty(entity.getTimezone())) {
            format.setTimeZone(TimeZone.getTimeZone(entity.getTimezone()));
        }
        value = format.format(temp);
    }
    return value;
}

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = false)/*from   ww w . j  ava 2  s.co m*/
public String reserver(final LocalDate date, final int individuId, final Famille famille, final Boolean reserve)
        throws FunctionalException, TechnicalException {
    final LocalDateTime heureResa = this.getLimiteResaCantine(date);
    if (!heureResa.isAfter(LocalDateTime.now())) {
        throw new ActNonModifiableException("activite non reservable");
    }
    final Date d = Date.from(Instant.from(date.atStartOfDay(ZoneId.systemDefault())));
    final Activite activite = getCantineActivite();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);
    final Inscription ict = icts.stream().filter(i -> individuId == i.getIndividu().getId()).findFirst().get();
    final List<Consommation> consos = this.consommationRepository.findByInscriptionActiviteUniteDate(ict,
            activite, ict.getGroupe(), d);
    final Unite unite = this.uniteRepository.findOneByActiviteAndType(ict.getActivite(), "Unitaire");
    if ((reserve == null && consos != null && !consos.isEmpty())
            || (reserve != null && reserve == false && consos != null && !consos.isEmpty())) {
        consos.forEach(c -> this.consommationRepository.delete(c));
        return "libre";
        // on supprime la conso
    } else if ((reserve == null && (consos == null || consos.isEmpty()))
            || (reserve == true && (consos == null || consos.isEmpty()))) {
        // cree la conso
        final Consommation conso = new Consommation();
        conso.setActivite(activite);
        conso.setDate(d);
        conso.setDateSaisie(new Date());
        conso.setEtat("reservation");
        conso.setGroupe(ict.getGroupe());
        conso.setIndividu(ict.getIndividu());
        conso.setInscription(ict);
        conso.setComptePayeur(ict.getComptePayeur());
        conso.setCategorieTarif(ict.getCategorieTarif());
        conso.setUnite(unite);
        conso.setHeureDebut(unite.getHeureDebut());
        conso.setHeureFin(unite.getHeureFin());

        this.consommationRepository.save(conso);
        return "reserve";
    }
    return "rien";

}

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = false)//from w w  w .  j  av a2  s  .c  o  m
public void reserver(final LocalDate startDate, final Famille famille, final List<DayOfWeek> jours)
        throws TechnicalException {

    final Activite activite = getCantineActivite();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);
    icts.forEach(ict -> {
        final List<Ouverture> ouvertures = this.ouvertureRepository.findByActiviteAndGroupeAndDateDebut(
                activite, ict.getGroupe(),
                Date.from(Instant.from(startDate.atStartOfDay(ZoneId.systemDefault()))));
        ouvertures.forEach(o -> {
            final LocalDate date = LocalDate.from(((java.sql.Date) o.getDate()).toLocalDate());
            try {
                this.reserver(date, ict.getIndividu().getId(), famille, jours.contains(date.getDayOfWeek()));
            } catch (TechnicalException e) {
                LOGGER.error("Une erreur technique s'est produite : " + e.getMessage(), e);
            } catch (FunctionalException e) {
                LOGGER.warn("Une erreur fonctionnelle s'est produite : " + e.getMessage(), e);
            }
        });
    });
}

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = true)//w  w w. j  av a 2s. c  o m
public List<DayOfWeek> getJourOuvertCantine(final LocalDate startDate, final Famille famille)
        throws TechnicalException {
    final List<DayOfWeek> jours = new ArrayList<>();
    final Activite activite = getCantineActivite();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);
    icts.forEach(ict -> {
        final List<Ouverture> ouvertures = this.ouvertureRepository.findByActiviteAndGroupeAndDateDebut(
                activite, ict.getGroupe(),
                Date.from(Instant.from(startDate.atStartOfDay(ZoneId.systemDefault()))));
        ouvertures.forEach(o -> {
            final LocalDate date = LocalDate.from(((java.sql.Date) o.getDate()).toLocalDate());
            if (!jours.contains(date.getDayOfWeek())) {
                jours.add(date.getDayOfWeek());
            }
        });
    });

    return jours;
}

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

/**
 * copy participant info/*from   www  .java  2s.co m*/
 */
private ParticipantType copyParticipant(ObjectFactory factory, Participant part) {
    final ParticipantType retVal = factory.createParticipantType();

    if (part.getId() != null)
        retVal.setId(part.getId());

    retVal.setName(part.getName());

    final LocalDate bday = part.getBirthDate();
    if (bday != null) {
        try {
            final DatatypeFactory df = DatatypeFactory.newInstance();
            final XMLGregorianCalendar cal = df
                    .newXMLGregorianCalendar(GregorianCalendar.from(bday.atStartOfDay(ZoneId.systemDefault())));
            cal.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
            retVal.setBirthday(cal);
        } catch (DatatypeConfigurationException e) {
            LOGGER.log(Level.WARNING, e.toString(), e);
        }
    }

    final Period age = part.getAge(null);
    if (age != null) {
        try {
            final DatatypeFactory df = DatatypeFactory.newInstance();
            final Duration ageDuration = df.newDuration(true, age.getYears(), age.getMonths(), age.getDays(), 0,
                    0, 0);
            retVal.setAge(ageDuration);
        } catch (DatatypeConfigurationException e) {
            LOGGER.log(Level.WARNING, e.toString(), e);
        }
    }

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

    final String lang = part.getLanguage();
    final String langs[] = (lang != null ? lang.split(",") : new String[0]);
    for (String l : langs) {
        retVal.getLanguage().add(StringUtils.strip(l));
    }

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

    ParticipantRole prole = part.getRole();
    if (prole == null)
        prole = ParticipantRole.TARGET_CHILD;
    retVal.setRole(prole.toString());

    // create ID based on role if possible
    if (retVal.getId() == null && prole != null) {
        if (prole == ParticipantRole.TARGET_CHILD) {
            retVal.setId("CHI");
        } else if (prole == ParticipantRole.MOTHER) {
            retVal.setId("MOT");
        } else if (prole == ParticipantRole.FATHER) {
            retVal.setId("FAT");
        } else if (prole == ParticipantRole.INTERVIEWER) {
            retVal.setId("INT");
        } else {
            retVal.setId("p" + (++pIdx));
        }
    }

    retVal.setSES(part.getSES());

    return retVal;
}