Example usage for java.time.format DateTimeFormatter ofPattern

List of usage examples for java.time.format DateTimeFormatter ofPattern

Introduction

In this page you can find the example usage for java.time.format DateTimeFormatter ofPattern.

Prototype

public static DateTimeFormatter ofPattern(String pattern) 

Source Link

Document

Creates a formatter using the specified pattern.

Usage

From source file:alfio.util.EventUtil.java

public static String getGoogleCalendarURL(Event event, TicketCategory category, String description) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyMMdd'T'HHmmss");
    ZonedDateTime validityStart = Optional.ofNullable(category).map(TicketCategory::getTicketValidityStart)
            .map(d -> d.withZoneSameInstant(event.getZoneId())).orElse(event.getBegin());
    ZonedDateTime validityEnd = Optional.ofNullable(category).map(TicketCategory::getTicketValidityEnd)
            .map(d -> d.withZoneSameInstant(event.getZoneId())).orElse(event.getEnd());
    return UriComponentsBuilder.fromUriString("https://www.google.com/calendar/event")
            .queryParam("action", "TEMPLATE")
            .queryParam("dates", validityStart.format(formatter) + "/" + validityEnd.format(formatter))
            .queryParam("ctz", event.getTimeZone()).queryParam("text", event.getDisplayName())
            .queryParam("location", event.getLocation()).queryParam("detail", description).toUriString();
}

From source file:com.pawandubey.griffin.Griffin.java

private void initializeConfigurationSettings() throws NumberFormatException, IOException {

    String title = null, author = null, date = null, slug = null, layout = "post", category = null, tags = null;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));

    while (StringUtils.isEmpty(title)) {
        System.out.println("1. title :");
        title = br.readLine();/*w  w  w . ja  va  2  s.  co  m*/
    }

    while (StringUtils.isEmpty(author)) {
        System.out.println("2. your name : (default is " + config.getSiteAuthor() + ",press Enter omit!)");
        author = br.readLine();
        if (StringUtils.isBlank(author)) {
            author = config.getSiteAuthor();
        }
    }
    while (StringUtils.isEmpty(slug)) {
        System.out.println("3. url :");
        slug = br.readLine();
    }

    while (StringUtils.isEmpty(category)) {
        System.out.println("4. category : (" + config.getCategories() + ",pick one or create new !):");
        category = br.readLine();
    }
    while (StringUtils.isEmpty(tags)) {
        System.out.println("5. tag : eg: tag1,tag2");
        tags = br.readLine();
    }

    while (StringUtils.isEmpty(date)) {
        System.out.println(
                "6. write date :  (format :" + config.getInputDateFormat() + ",press Enter user today.)");
        date = br.readLine();
        if (StringUtils.isEmpty(date)) {
            date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(config.getInputDateFormat()));
        }
    }

    ;

    Path draftPath = Paths.get(config.getSourceDir())
            .resolve(title.replaceAll("\\s+|;|\\)|\\(|&", "-") + ".markdown");
    String content = postTemplate.replace("#title", title).replace("#date", date).replace("#category", category)
            .replace("#layout", layout).replace("#author", author).replace("#tags", formatTag(tags))
            .replace("#slug", slug);

    try (BufferedWriter bw = Files.newBufferedWriter(draftPath, StandardCharsets.UTF_8)) {
        bw.write(content);
    } catch (IOException ex) {
        Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("draft path [" + draftPath + "]");
    System.out.println("*******************************************************************");
    System.out.println(content);
    System.out.println("*******************************************************************");
    System.out.println("draft path [" + draftPath + "]");

}

From source file:com.buffalokiwi.api.APIDate.java

/**
 * Retrieve the local date as a string./*from  w w w .j av a2  s  .  c  o  m*/
 * This does NOT include zone information
 * @return date/time
 */
@Override
public String getLocalDateString() {
    return date.withZoneSameInstant(offset).format(DateTimeFormatter.ofPattern(FMT_LOCAL));
}

From source file:investiagenofx2.view.InvestiaGenOFXController.java

/**
 * Initializes the controller class./*from w  w  w .j  a v a  2 s  .c o  m*/
 *
 * @param url
 * @param rb
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    txt_investiaURL.setText(PropertiesInit.getInvestiaURL());
    dtp_lastDate.setValue(LocalDate.parse(PropertiesInit.getLastGenUsedDate()));
    String[] clientNums = PropertiesInit.getClientNumList().split(",");
    for (String clientNum : clientNums) {
        if (!clientNum.trim().isEmpty()) {
            cbo_clientNum.getItems().add(clientNum.trim());
        }
    }
    Arrays.fill(linkAccountToLocalAccountIndex, -1);
    resetControls();

    cbo_clientNum.getEditor().addEventFilter(KeyEvent.KEY_PRESSED, event -> {
        if (event.getCode() == KeyCode.DELETE) {
            cbo_clientNum.getItems().remove(cbo_clientNum.getValue());
            event.consume();
        }
    });

    dtp_lastDate.setConverter(new StringConverter<LocalDate>() {
        final String pattern = "yyyy-MM-dd";
        final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);

        {
            dtp_lastDate.setPromptText(pattern.toLowerCase());
        }

        @Override
        public String toString(LocalDate date) {
            if (date != null) {
                return dateFormatter.format(date);
            } else {
                return "";
            }
        }

        @Override
        public LocalDate fromString(String string) {
            if (string != null && !string.isEmpty()) {
                return LocalDate.parse(string, dateFormatter);
            } else {
                return null;
            }
        }
    });

    //This deals with the bug located here where the datepicker value is not updated on focus lost
    //https://bugs.openjdk.java.net/browse/JDK-8092295?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
    dtp_lastDate.focusedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (!newValue) {
                dtp_lastDate
                        .setValue(dtp_lastDate.getConverter().fromString(dtp_lastDate.getEditor().getText()));
            }
        }
    });
}

From source file:it.tidalwave.northernwind.frontend.ui.component.sitemap.DefaultSitemapViewController.java

/*******************************************************************************************************************
 *
 *
 ******************************************************************************************************************/
private void appendUrl(final @Nonnull StringBuilder builder, final @Nonnull SiteNode siteNode,
        final @Nullable SiteNode childSiteNode) throws IOException {
    final SiteNode n = (childSiteNode != null) ? childSiteNode : siteNode;
    final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    final ResourceProperties properties = n.getProperties();
    //// ww  w . ja  v  a2 s.  c o  m
    // FIXME: if you put the sitemap property straightly into the child site node, you can simplify a lot,
    // just using a single property and only peeking into a single node
    final Key<String> priorityKey = (childSiteNode == null) ? PROPERTY_SITEMAP_PRIORITY
            : PROPERTY_SITEMAP_CHILDREN_PRIORITY;
    final float sitemapPriority = Float.parseFloat(siteNode.getProperties().getProperty(priorityKey, "0.5"));

    if (sitemapPriority > 0) {
        builder.append("  <url>\n");
        builder.append(String.format("    <loc>%s</loc>%n", site.createLink(n.getRelativeUri())));
        builder.append(String.format("    <lastmod>%s</lastmod>%n",
                getSiteNodeDateTime(properties).format(dateTimeFormatter)));
        builder.append(String.format("    <changefreq>%s</changefreq>%n",
                properties.getProperty(PROPERTY_SITEMAP_CHANGE_FREQUENCY, "daily")));
        builder.append(String.format("    <priority>%s</priority>%n", Float.toString(sitemapPriority)));
        builder.append("  </url>\n");
    }
}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Converts the given election object to a Json String. The Json string is then signed.
 * The resulting JWS gets posted to the bulletin board
 * @param election//from  w ww . jav  a2  s  .  com
 * election object to be posted to the bulletin board
 */
public void postElection(Election election) {
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    //Add Header information to the json object
    //TODO get email address from certificate 
    jBuilder.add("author", "alice@bfh.ch");
    jBuilder.add("electionTitle", election.getTitle());
    jBuilder.add("beginDate", election.getStartDate().format(format));
    jBuilder.add("endDate", election.getEndDate().format(format));
    //toDo: get AppVersion dynamically from build 
    jBuilder.add("appVersion", "0.15");

    jBuilder.add("coefficients", election.getCredentialPolynomialString());
    jBuilder.add("electionGenerator", election.getH_HatString());

    //Add votingTopic to the Json Object
    JsonObjectBuilder votingTopicBuilder = Json.createObjectBuilder();
    votingTopicBuilder.add("topic", election.getTopic().getTitle());
    votingTopicBuilder.add("pick", election.getTopic().getPick());

    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();
    for (String option : election.getTopic().getOptions()) {
        optionsBuilder.add(option);
    }
    votingTopicBuilder.add("options", optionsBuilder);

    jBuilder.add("votingTopic", votingTopicBuilder);

    //Add the list of selected Voters to the Json object
    JsonArrayBuilder votersBuilder = Json.createArrayBuilder();

    for (Voter voter : election.getVoterList()) {
        JsonObjectBuilder voterBuilder = Json.createObjectBuilder();
        voterBuilder.add("email", voter.getEmail());
        voterBuilder.add("publicCredential", voter.getPublicCredential());
        voterBuilder.add("appVersion", voter.getAppVersion());

        votersBuilder.add(voterBuilder);
    }

    jBuilder.add("voters", votersBuilder);

    JsonObject model = jBuilder.build();
    //finished Json gets singed
    SignatureController signController = new SignatureController();
    JsonObject signedModel = null;

    try {
        signedModel = signController.signJson(model);
    } catch (Exception ex) {
        Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
    }

    //JWS gets posted to the bulletin board
    try {
        boolean requestOK = postJsonStringToURL(bulletinBoardUrl + "/elections", signedModel.toString(), false);
        if (requestOK) {
            System.out.println("Election posted!");
        } else {
            System.out.println("Was not able to post Election! Did not receive expected http 200 status.");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Election! IOException");
    }

}

From source file:org.codelibs.fess.service.SearchLogService.java

public void deleteAll(final SearchLogPager searchLogPager) {
    clickLogBhv.varyingQueryDelete(cb2 -> {
        if (StringUtil.isNotBlank(searchLogPager.searchWord)) {
            cb2.query().querySearchLog().setSearchWord_LikeSearch(searchLogPager.searchWord,
                    op -> op.likeContain());
        }//ww  w.  ja v  a2 s .com

        if (StringUtil.isNotBlank(searchLogPager.startDate)) {
            final StringBuilder buf = new StringBuilder(20);
            buf.append(searchLogPager.startDate);
            buf.append('+');
            if (StringUtil.isNotBlank(searchLogPager.startHour)) {
                buf.append(searchLogPager.startHour);
            } else {
                buf.append("00");
            }
            buf.append(':');
            if (StringUtil.isNotBlank(searchLogPager.startMin)) {
                buf.append(searchLogPager.startMin);
            } else {
                buf.append("00");
            }

            final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd+HH:mm");
            try {
                final LocalDateTime startDate = LocalDateTime.parse(buf.toString(), formatter);
                cb2.query().querySearchLog().setRequestedTime_GreaterEqual(startDate);
            } catch (final DateTimeParseException e) {
                searchLogPager.startDate = null;
                searchLogPager.startHour = null;
                searchLogPager.startMin = null;
            }
        }

        if (StringUtil.isNotBlank(searchLogPager.endDate)) {
            final StringBuilder buf = new StringBuilder(20);
            buf.append(searchLogPager.endDate);
            buf.append('+');
            if (StringUtil.isNotBlank(searchLogPager.endHour)) {
                buf.append(searchLogPager.endHour);
            } else {
                buf.append("00");
            }
            buf.append(':');
            if (StringUtil.isNotBlank(searchLogPager.endMin)) {
                buf.append(searchLogPager.endMin);
            } else {
                buf.append("00");
            }

            final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd+HH:mm");
            try {
                final LocalDateTime endDate = LocalDateTime.parse(buf.toString(), formatter);
                cb2.query().querySearchLog().setRequestedTime_LessThan(endDate);
            } catch (final DateTimeParseException e) {
                searchLogPager.endDate = null;
                searchLogPager.endHour = null;
                searchLogPager.endMin = null;
            }
        }

        if (StringUtil.isNotBlank(searchLogPager.startPage)) {
            cb2.query().querySearchLog().setQueryOffset_Equal(0);
        }
    }, op -> op.allowNonQueryDelete());
    searchFieldLogBhv.varyingQueryDelete(cb2 -> {
    }, op -> op.allowNonQueryDelete());
    searchLogBhv.varyingQueryDelete(cb1 -> {
        if (StringUtil.isNotBlank(searchLogPager.searchWord)) {
            cb1.query().setSearchWord_LikeSearch(searchLogPager.searchWord, op -> op.likeContain());
        }

        if (StringUtil.isNotBlank(searchLogPager.userCode)) {
            cb1.setupSelect_UserInfo();
            cb1.query().queryUserInfo().setCode_Equal(searchLogPager.userCode);
        }

        if (StringUtil.isNotBlank(searchLogPager.startDate)) {
            final StringBuilder buf = new StringBuilder(20);
            buf.append(searchLogPager.startDate);
            buf.append('+');
            if (StringUtil.isNotBlank(searchLogPager.startHour)) {
                buf.append(searchLogPager.startHour);
            } else {
                buf.append("00");
            }
            buf.append(':');
            if (StringUtil.isNotBlank(searchLogPager.startMin)) {
                buf.append(searchLogPager.startMin);
            } else {
                buf.append("00");
            }

            final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd+HH:mm");
            try {
                final LocalDateTime startDate = LocalDateTime.parse(buf.toString(), formatter);
                cb1.query().setRequestedTime_GreaterEqual(startDate);
            } catch (final DateTimeParseException e) {
                searchLogPager.startDate = null;
                searchLogPager.startHour = null;
                searchLogPager.startMin = null;
            }
        }

        if (StringUtil.isNotBlank(searchLogPager.endDate)) {
            final StringBuilder buf = new StringBuilder(20);
            buf.append(searchLogPager.endDate);
            buf.append('+');
            if (StringUtil.isNotBlank(searchLogPager.endHour)) {
                buf.append(searchLogPager.endHour);
            } else {
                buf.append("00");
            }
            buf.append(':');
            if (StringUtil.isNotBlank(searchLogPager.endMin)) {
                buf.append(searchLogPager.endMin);
            } else {
                buf.append("00");
            }

            final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd+HH:mm");
            try {
                final LocalDateTime endDate = LocalDateTime.parse(buf.toString(), formatter);
                cb1.query().setRequestedTime_LessThan(endDate);
            } catch (final DateTimeParseException e) {
                searchLogPager.endDate = null;
                searchLogPager.endHour = null;
                searchLogPager.endMin = null;
            }
        }

        if (StringUtil.isNotBlank(searchLogPager.startPage)) {
            cb1.query().setQueryOffset_Equal(0);
        }
    }, op -> op.allowNonQueryDelete());
}

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

@Override
public void refreshAllPages(List<String> validDates, String apiGatewayBaseUrl, String revvingSuffix)
        throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The page manager has not been initialised");
    }//  www .j av a 2  s .c  om

    try {
        // Upload all bookings pages, cached booking data, famous players data,
        // and the index page to the S3 bucket. N.B. This should upload for the
        // most-future date first to ensure all links are valid during the several
        // seconds the update takes to complete.
        logger.log("About to refresh S3 website");
        logger.log("Using valid dates: " + validDates);
        logger.log("Using ApigatewayBaseUrl: " + apiGatewayBaseUrl);

        // Log time to sanity check it does occur at midnight. (_Think_ this
        // accounts for BST?). N.B. Manual executions may be at other times.
        logger.log("Current London time is: " + Calendar.getInstance().getTime().toInstant()
                .atZone(TimeZone.getTimeZone("Europe/London").toZoneId())
                .format(DateTimeFormatter.ofPattern("h:mm a")));

        ImmutablePair<ILifecycleManager.LifecycleState, Optional<String>> lifecycleState = lifecycleManager
                .getLifecycleState();

        uploadBookingsPagesToS3(validDates, apiGatewayBaseUrl, revvingSuffix, lifecycleState);
        logger.log("Uploaded new set of bookings pages to S3");

        // Save the valid dates in JSON form
        logger.log("About to create and upload cached valid dates data to S3");
        copyJsonDataToS3("NoScript/validdates", createValidDatesData(validDates));
        logger.log("Uploaded cached valid dates data to S3");

        logger.log("About to upload famous players data to S3");
        uploadFamousPlayers();
        logger.log("Uploaded famous players data to S3");

        // Remove the now-previous day's bookings page and cached data from S3.
        // (If this page does not exist then this is a no-op.)
        String yesterdaysDate = getCurrentLocalDate().minusDays(1)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        logger.log("About to remove yesterday's booking page and cached data from S3 bucket: "
                + websiteBucketName + " and key: " + yesterdaysDate + ".html");
        IS3TransferManager transferManager = getS3TransferManager();
        DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(websiteBucketName,
                yesterdaysDate + ".html");
        AmazonS3 client = transferManager.getAmazonS3Client();
        client.deleteObject(deleteObjectRequest);
        deleteObjectRequest = new DeleteObjectRequest(websiteBucketName, yesterdaysDate + ".json");
        client.deleteObject(deleteObjectRequest);
        logger.log("Removed yesterday's booking page and cached data successfully from S3");
    } catch (Exception exception) {
        logger.log("Exception caught while refreshing S3 booking pages - so notifying sns topic");
        getSNSClient().publish(adminSnsTopicArn,
                "Apologies - but there was an error refreshing the booking pages in S3. Please refresh the pages manually instead from the Lambda console. The error message was: "
                        + exception.getMessage(),
                "Sqawsh booking pages in S3 failed to refresh");
        // Rethrow
        throw exception;
    }
}

From source file:br.com.webbudget.domain.model.service.PeriodDetailService.java

/**
 * Metodo que monta o modelo do grafico de consumo por dia no periodo
 *
 * @param period o periodo/*from  www .  j a  v a 2s  .  c om*/
 * @return o model para a view
 */
public LineChartModel bulidDailyChart(FinancialPeriod period) {

    // lista receitas e despesas do periodo
    final List<Movement> revenues = this.listMovementsFrom(period, MovementClassType.IN);
    final List<Movement> expenses = this.listMovementsFrom(period, MovementClassType.OUT);

    // agrupamos pelas datas das despesas e receitas
    final List<LocalDate> payDates = this.groupPaymentDates(ListUtils.union(revenues, expenses));

    // monta o grafico de linhas
    final LineChartModel model = new LineChartModel();

    // dados de despesas
    final LineChartDatasetBuilder<BigDecimal> expensesBuilder = new LineChartDatasetBuilder<>()
            .filledByColor("rgba(255,153,153,0.2)").withStrokeColor("rgba(255,77,77,1)")
            .withPointColor("rgba(204,0,0,1)").withPointStrokeColor("#fff").withPointHighlightFillColor("#fff")
            .withPointHighlightStroke("rgba(204,0,0,1)");

    // dados de receitas
    final LineChartDatasetBuilder<BigDecimal> revenuesBuilder = new LineChartDatasetBuilder<>()
            .filledByColor("rgba(140,217,140,0.2)").withStrokeColor("rgba(51,153,51,1)")
            .withPointColor("rgba(45,134,45,1)").withPointStrokeColor("#fff")
            .withPointHighlightFillColor("#fff").withPointHighlightStroke("rgba(45,134,45,1)");

    // para cada data de pagamento, printa o valor no dataset
    payDates.stream().forEach(payDate -> {

        model.addLabel(DateTimeFormatter.ofPattern("dd/MM").format(payDate));

        final BigDecimal expensesTotal = expenses.stream()
                .filter(movement -> movement.getPaymentDate().equals(payDate)).map(Movement::getValue)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        final BigDecimal revenuesTotal = revenues.stream()
                .filter(movement -> movement.getPaymentDate().equals(payDate)).map(Movement::getValue)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        expensesBuilder.andData(expensesTotal);
        revenuesBuilder.andData(revenuesTotal);
    });

    // joga os datasets no model
    model.addDataset(revenuesBuilder.build());
    model.addDataset(expensesBuilder.build());

    return model;
}

From source file:com.epam.parso.impl.CSVDataWriterImpl.java

/**
 * The function to convert a Java 8 LocalDateTime into a string according to the format used.
 *
 * @param currentDate the LocalDateTime to convert.
 * @param format      the string with the format that must belong to the set of
 *                    {@link CSVDataWriterImpl#DATE_OUTPUT_FORMAT_STRINGS} mapping keys.
 * @return the string that corresponds to the date in the format used.
 *//*ww w  .  j a  v a  2s.  c  o  m*/
protected static String convertLocalDateTimeElementToString(LocalDateTime currentDate, String format) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_OUTPUT_FORMAT_STRINGS.get(format));
    String valueToPrint = "";
    ZonedDateTime zonedDateTime = currentDate.atZone(ZoneOffset.UTC);
    if (zonedDateTime.toInstant().toEpochMilli() != 0 && zonedDateTime.getNano() != 0) {
        valueToPrint = formatter.format(currentDate);
    }
    return valueToPrint;
}