Home > Back-end >  convert from localdate to string in spring boot
convert from localdate to string in spring boot

Time:06-20

I want to convert a localdate "StartDate" to string so I can concatenate without a problem but the methode format doesn't work this is my service where the problem is:

    List<DatesRequest> datesRequests = PaidRequest.getDatesRequest();
    String StartDate = datesRequests.stream().map(DatesRequest::getStartDate).format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
            CollaboratorDTO validator = OrganizationalUintService.findValidator(collaboratorTransformer.entityTranferToDTO(PaidRequest.getCollaborator()));
        EmailService.sendSimpleMessage(validator.getEmail(),
                "EverHoliday",
                " Bonjour " validator.getFirstname() " " validator.getLastname() ","
                  " \n "  PaidRequest.getCollaborator().getLastname() " "  PaidRequest.getCollaborator().getFirstname() 
                " a ajouté une demande de congé du  " StartDate  " en attente de votre approbation "
                  " \n Cordialement.");

String StartDate = datesRequests.stream().map(DatesRequest::getStartDate).format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); the error that show up is "Cannot resolve method 'format' in 'Stream'"

CodePudding user response:

The error message describes the issue. Method .format is absent at Stream interface. see https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html I think that you want to transform the object to string and concatenate it. So:

String StartDate = datesRequests.stream().map(DatesRequest::getStartDate).map(date -> DateTimeFormatter.ofPattern("dd/MM/yyyy").format(date)).collect(Collectors.joining(","));

CodePudding user response:

If your startDate is LocalDateTime type, you can format it like this:

List<String> collect = datesRequests.stream().map(DatesRequest::getStartDate).stream().map(d -> {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); // Usually we new the formatter outside of the stream 
        return d.format(dateTimeFormatter);
    }).collect(Collectors.toList());

Please note that your input is a list, so you need to accumulate the elements.

  • Related