Example usage for java.time LocalDate parse

List of usage examples for java.time LocalDate parse

Introduction

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

Prototype

public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) 

Source Link

Document

Obtains an instance of LocalDate from a text string using a specific formatter.

Usage

From source file:squash.booking.lambdas.core.BookingManagerTest.java

private List<Booking> expectOptimisticPersisterGetAllItemsToReturnAllBookings(boolean addNonBookingItems) {
    // (the version number must be set here but its value is irrelevant)
    List<ImmutablePair<String, List<Attribute>>> expectedDateAttributeListPairs = new ArrayList<>();
    List<Attribute> attributes = new ArrayList<>();
    // Add bookings that are not all on a single day.
    List<Booking> bookingsForMoreThanOneDay = new ArrayList<>();
    bookingsForMoreThanOneDay.add(existingSingleBooking);
    Booking bookingForAnotherDay = new Booking(existingSingleBooking);
    bookingForAnotherDay/*  www.ja  va 2 s  . c  om*/
            .setDate(LocalDate.parse(existingSingleBooking.getDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                    .minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    bookingsForMoreThanOneDay.add(bookingForAnotherDay);

    bookingsForMoreThanOneDay.stream().forEach(booking -> {
        attributes.add(new Attribute(
                booking.getCourt().toString() + "-" + booking.getCourtSpan().toString() + "-"
                        + booking.getSlot().toString() + "-" + booking.getSlotSpan().toString(),
                booking.getName()));
        expectedDateAttributeListPairs.add(new ImmutablePair<>(booking.getDate(), attributes));
    });

    if (addNonBookingItems) {
        // OptimisticPersister also has items for booking rules and lifecycle
        // state. The booking manager should ignore these items when returning the
        // bookings.
        List<Attribute> nonBookingAttributes = new ArrayList<>();
        nonBookingAttributes.add(new Attribute("Some attribute name", "Some arbitrary value"));
        expectedDateAttributeListPairs.add(new ImmutablePair<>("LifecycleState", nonBookingAttributes));
        expectedDateAttributeListPairs
                .add(new ImmutablePair<>("BookingRulesAndExclusions", nonBookingAttributes));
    }

    // Set up mock optimistic persister to return these bookings - or to throw
    mockery.checking(new Expectations() {
        {
            oneOf(mockOptimisticPersister).getAllItems();
            will(returnValue(expectedDateAttributeListPairs));
        }
    });
    bookingManager.setOptimisticPersister(mockOptimisticPersister);

    return bookingsForMoreThanOneDay;
}

From source file:jp.co.opentone.bsol.linkbinder.service.correspon.impl.CorresponFullTextSearchServiceImpl.java

protected boolean isAcceptableDateString(String keyword) {
    final DateTimeFormatter acceptableFormats[] = { DateTimeFormatter.ofPattern("yyyy-MM-dd"),
            DateTimeFormatter.ofPattern("yyyyMMdd") };

    return Stream.of(StringUtils.split(keyword, ' ')).allMatch(s -> {
        String str = StringUtils.trim(s);
        boolean parsed = false;
        for (DateTimeFormatter f : acceptableFormats) {
            try {
                LocalDate.parse(str, f);
                parsed = true;//from  ww w .ja  va2 s. com
                break;
            } catch (DateTimeParseException ignore) {
            }
        }
        return parsed;
    });
}

From source file:lumbermill.internal.elasticsearch.ElasticSearchOkHttpClientImpl.java

private String indexRowWithDateAndType(JsonEvent event) {

    Optional<String> formattedType = type.format(event);
    if (!formattedType.isPresent()) {
        throw new IllegalStateException(
                "Issue with type, could not extract field from event " + type.original());
    }//from w  w w.  j a v  a2  s  .c om

    Optional<String> formattedIndex = index.format(event);
    if (!formattedIndex.isPresent()) {
        throw new IllegalStateException(
                "Issue with index, could not extract field from event: " + index.original());
    }

    Optional<String> formattedDocumentId = Optional.empty();
    if (documentId.isPresent()) {
        formattedDocumentId = documentId.get().format(event);
        if (!formattedDocumentId.isPresent()) {
            throw new IllegalStateException(
                    "Issue with index, could not extract field from event: " + index.original());
        }
    }

    ObjectNode objectNode = OBJECT_MAPPER.createObjectNode();
    ObjectNode data = OBJECT_MAPPER.createObjectNode();

    // Prepare for adding day to index for each event
    if (indexIsPrefix) {
        LocalDate indexDate;
        // TODO: Not sure how to handle this... what should be the behaviour if the specified timestamp field
        //       does not exist
        if (event.has(this.timestampField)) {
            indexDate = LocalDate.parse(event.valueAsString(this.timestampField).substring(0, 10),
                    DateTimeFormatter.ISO_DATE);
        } else {
            indexDate = LocalDate.now();
        }
        data.put("_index", formattedIndex.get() + indexDate.format(DateTimeFormatter.ofPattern("yyyy.MM.dd")));
    } else {
        data.put("_index", formattedIndex.get());
    }
    data.put("_type", formattedType.get());

    if (formattedDocumentId.isPresent()) {
        data.put("_id", formattedDocumentId.get());
    }
    objectNode.set("index", data);

    return objectNode.toString();
}

From source file:org.tightblog.util.Utilities.java

/**
 * Parse date as either 6-char or 8-char format.  Use current date if date not provided
 * in URL (e.g., a permalink), more than 30 days in the future, or not valid
 *///from   ww  w . j ava2  s .  co  m
public static LocalDate parseURLDate(String dateString) {
    LocalDate ret = null;

    try {
        if (StringUtils.isNumeric(dateString)) {
            if (dateString.length() == 8) {
                ret = LocalDate.parse(dateString, Utilities.YMD_FORMATTER);
            } else if (dateString.length() == 6) {
                YearMonth tmp = YearMonth.parse(dateString, Utilities.YM_FORMATTER);
                ret = tmp.atDay(1);
            }
        }
    } catch (DateTimeParseException ignored) {
        ret = null;
    }

    // make sure the requested date is not more than a month in the future
    if (ret == null || ret.isAfter(LocalDate.now().plusDays(30))) {
        ret = LocalDate.now();
    }

    return ret;
}

From source file:com.actelion.research.spiritcore.services.SampleListValidator.java

private boolean checkDateFormat(String[][] data, int col) throws Exception {
    DateTimeFormatter dtf = dtfBuilder.toFormatter();
    DateTimeFormatter outDateFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
    for (int i = 1; i < data.length; i++) {
        try {//from w w w  .j av a2s  .  c o m
            if (col >= data[i].length || data[i][col] == null || data[i][col].isEmpty()) {
                continue;
            }
            LocalDate inDate = LocalDate.parse(data[i][col], dtf);
            data[i][col] = inDate.format(outDateFormatter);
        } catch (DateTimeParseException dtpe) {
            specificErrorMessage = "Found value '" + data[i][col] + "' at line " + (i + 1);
            throw new Exception("Some dates are not in the format '" + Arrays.toString(dtPatterns) + "'.\r\n"
                    + specificErrorMessage);
        }
    }

    return true;
}

From source file:org.gradoop.flink.datagen.transactions.foodbroker.config.FoodBrokerConfig.java

/**
 * Loads the start date./*w w w .  j ava 2  s .co  m*/
 *
 * @return long representation of the start date
 */
public LocalDate getStartDate() {
    String startDate;
    DateTimeFormatter formatter;
    LocalDate date = LocalDate.MIN;

    try {
        startDate = root.getJSONObject("Process").getString("startDate");
        formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        date = LocalDate.parse(startDate, formatter);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return date;
}

From source file:agendavital.modelo.data.Noticia.java

public static TreeMap<LocalDate, ArrayList<Noticia>> buscar(String _parametro)
        throws ConexionBDIncorrecta, SQLException {
    final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    ArrayList<String> _tags = UtilidadesBusqueda.separarPalabras(_parametro);
    TreeMap<LocalDate, ArrayList<Noticia>> busqueda = null;
    try (Connection conexion = ConfigBD.conectar()) {
        busqueda = new TreeMap<>();
        for (String _tag : _tags) {
            String tag = ConfigBD.String2Sql(_tag, true);
            String buscar = String.format("SELECT id_Noticia, fecha from noticias "
                    + "WHERE id_noticia IN (SELECT id_noticia from momentos_noticias_etiquetas "
                    + "WHERE id_etiqueta IN (SELECT id_etiqueta from etiquetas WHERE nombre LIKE %s)) "
                    + "OR titulo LIKE %s " + "OR cuerpo LIKE %s " + "OR categoria LIKE %s "
                    + "OR fecha LIKE %s; ", tag, tag, tag, tag, tag);
            ResultSet rs = conexion.createStatement().executeQuery(buscar);
            while (rs.next()) {
                LocalDate date = LocalDate.parse(rs.getString("fecha"), dateFormatter);
                Noticia insertarNoticia = new Noticia(rs.getInt("id_noticia"));
                if (busqueda.containsKey(date)) {
                    boolean encontrado = false;
                    for (int i = 0; i < busqueda.get(date).size() && !encontrado; i++)
                        if (busqueda.get(date).get(i).getId() == insertarNoticia.getId())
                            encontrado = true;
                    if (!encontrado)
                        busqueda.get(date).add(insertarNoticia);
                } else {
                    busqueda.put(date, new ArrayList<>());
                    busqueda.get(date).add(insertarNoticia);
                }//  ww w  .  j av  a  2 s.c om
            }

        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    Iterator it = busqueda.keySet().iterator();
    return busqueda;
}

From source file:com.acapulcoapp.alloggiatiweb.FileReader.java

public static Person extractPerson(String line) {
    Person p = new Person();
    //        String part = line.substring(start, start + COGNOME.getLength()).trim().toLowerCase();
    //        if (containsSpecialChar(part)) {
    //            part = part.substring(0, part.length() - 1).trim().toLowerCase();
    //            start--;
    //        }/*from  w  ww .j  a v a2s .com*/

    p.setSurname(COGNOME.parse(line));

    p.setName(NOME.parse(line));

    String part = SESSO.parse(line);
    p.setGender(part.equals("1") ? Gender.male : Gender.female);

    part = DATA_NASCITA.parse(line);
    p.setDateOfBirth(LocalDate.parse(part, DateTimeFormatter.ofPattern(DATE_PATTERN)));

    part = COMUNE_NASCITA.parse(line);
    District d = districtRepository.find(part);
    p.setDistrictOfBirth(d);

    part = STATO_NASCITA.parse(line);
    Country c = countryRepository.find(part);
    p.setCountryOfBirth(c);

    part = CITTADINANZA.parse(line);
    c = countryRepository.find(part);
    p.setCitizenship(c);

    part = TIPO_DOCUMENTO.parse(line);
    IdentityDocument id = identityDocumentRepository.find(part);
    p.setIdentityDocument(id);

    part = NUMERO_DOCUMENTO.parse(line);
    if (!part.isEmpty()) {
        p.setDocumentNumber(part);
    }

    part = LUOGO_RILASCIO.parse(line);
    d = districtRepository.find(part);
    p.setDocumentReleaseDistrict(d);
    if (d == null) {
        c = countryRepository.find(part);
        p.setDocumentReleaseCountry(c);
    }

    return p;
}

From source file:org.silverpeas.core.util.DateUtil.java

public static LocalDate toLocalDate(String date) {
    return LocalDate.parse(date, CUSTOM_FORMATTER);
}

From source file:investiagenofx2.view.InvestiaGenOFXController.java

private void getAccountsFromWeb() {
    String name = "Nom Pastrouv";
    try {//from  w w w  . j av  a2s.  c  o  m
        name = ((HtmlDivision) htmlPage.getHtmlElementById("phase1CustomerName")).asText();
        name = name.replace("Mme ", "").trim();
        name = name.replace("M. ", "").trim();
    } catch (ElementNotFoundException ex) {
        try {
            name = ((HtmlSelect) htmlPage.getHtmlElementById("selAccount")).asText();
            name = name.replaceAll("[^A-Za-z ]", "").trim();
        } catch (ElementNotFoundException ex2) {
        }
    }
    name = capitalizeFully(name);
    String[] token = name.split(" ");
    accountOwnerName = token[0] + " " + token[1];
    token = ((HtmlDivision) htmlPage.getByXPath("//div[contains(@class, 'col-xs-4 text-right')]").get(0))
            .asText().split(" ");
    dataAsDate = LocalDate.parse(token[token.length - 1], DateTimeFormatter.ISO_DATE);
    accounts = new ArrayList<>();
    try {
        if (InvestiaGenOFX.debug) {
            htmlPage = InvestiaGenOFX.getWebClient().getPage(InvestiaGenOFX.debugFullPath + "-Investments.htm");
        } else {
            htmlPage = InvestiaGenOFX.getWebClient()
                    .getPage(txt_investiaURL.getText() + "/Investments/ValueOf" + "?wcag=true");
        }

        List<?> sections = htmlPage.getByXPath("//section[not(contains(@id, 'valueOf'))]");
        for (int i = 1; i < sections.size(); i++) {
            HtmlSection section = (HtmlSection) sections.get(i);
            HtmlHeading4 h4 = (HtmlHeading4) section.getElementsByTagName("h4").get(0);
            token = h4.asText().replaceAll("[\\\\,]", "").split(" - ");
            Account account = new Account(token[0], token[1], dataAsDate);
            try {
                HtmlHeading5 h5 = (HtmlHeading5) section.getElementsByTagName("h5").get(0);
                token = h5.asText().split(" ");
                if (token[0].startsWith("Numro")) {
                    account.setAccountID(token[token.length - 1]);
                }
            } catch (IndexOutOfBoundsException ex) {
            }
            addAccount(account);
        }
    } catch (Exception ex) {
        Logger.getLogger(InvestiaGenOFXController.class.getName()).log(Level.SEVERE, null, ex);
    }
}