Example usage for java.time.format DateTimeFormatter format

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

Introduction

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

Prototype

public String format(TemporalAccessor temporal) 

Source Link

Document

Formats a date-time object using this formatter.

Usage

From source file:org.jspare.ui.view.UIFormatter.java

/**
 * Format local date time./*from   w  w w .ja  v  a2 s. c o m*/
 *
 * @param value
 *            the value
 * @param pattern
 *            the pattern
 * @return the string
 */
public static String formatLocalDateTime(LocalDateTime value, String pattern) {

    if (value == null || StringUtils.isEmpty(pattern)) {

        return StringUtils.EMPTY;
    }

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
    return dateTimeFormatter.format(value);
}

From source file:Main.java

/**
 * Converts a LocalDate (ISO) value to a ChronoLocalDate date using the
 * provided Chronology, and then formats the ChronoLocalDate to a String using
 * a DateTimeFormatter with a SHORT pattern based on the Chronology and the
 * current Locale./* w ww. j a v a2  s  .co  m*/
 *
 * @param localDate
 *          - the ISO date to convert and format.
 * @param chrono
 *          - an optional Chronology. If null, then IsoChronology is used.
 */
public static String toString(LocalDate localDate, Chronology chrono) {
    if (localDate != null) {
        Locale locale = Locale.getDefault(Locale.Category.FORMAT);
        ChronoLocalDate cDate;
        if (chrono == null) {
            chrono = IsoChronology.INSTANCE;
        }
        try {
            cDate = chrono.date(localDate);
        } catch (DateTimeException ex) {
            System.err.println(ex);
            chrono = IsoChronology.INSTANCE;
            cDate = localDate;
        }
        String pattern = "M/d/yyyy GGGGG";
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);
        return dateFormatter.format(cDate);
    } else {
        return "";
    }
}

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.
 *//*from w  ww. j  a  va 2 s .  c om*/
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;
}

From source file:jgnash.convert.exportantur.csv.CsvExport.java

public static void exportAccount(final Account account, final LocalDate startDate, final LocalDate endDate,
        final File file) {
    Objects.requireNonNull(account);
    Objects.requireNonNull(startDate);
    Objects.requireNonNull(endDate);
    Objects.requireNonNull(file);

    // force a correct file extension
    final String fileName = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".csv";

    final CSVFormat csvFormat = CSVFormat.EXCEL.withQuoteMode(QuoteMode.ALL);

    try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
            Files.newOutputStream(Paths.get(fileName)), StandardCharsets.UTF_8);
            final CSVPrinter writer = new CSVPrinter(new BufferedWriter(outputStreamWriter), csvFormat)) {

        outputStreamWriter.write('\ufeff'); // write UTF-8 byte order mark to the file for easier imports

        writer.printRecord("Account", "Number", "Debit", "Credit", "Balance", "Date", "Timestamp", "Memo",
                "Payee", "Reconciled");

        // write the transactions
        final List<Transaction> transactions = account.getTransactions(startDate, endDate);

        final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendValue(MONTH_OF_YEAR, 2).appendValue(DAY_OF_MONTH, 2).toFormatter();

        final DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendLiteral('-').appendValue(MONTH_OF_YEAR, 2).appendLiteral('-')
                .appendValue(DAY_OF_MONTH, 2).appendLiteral(' ').appendValue(HOUR_OF_DAY, 2).appendLiteral(':')
                .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':').appendValue(SECOND_OF_MINUTE, 2)
                .toFormatter();//from   w w  w.  j  a  va2s  .com

        for (final Transaction transaction : transactions) {
            final String date = dateTimeFormatter.format(transaction.getLocalDate());

            final String timeStamp = timestampFormatter.format(transaction.getTimestamp());

            final String credit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) < 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String debit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) > 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String balance = account.getBalanceAt(transaction).toPlainString();

            final String reconciled = transaction.getReconciled(account) == ReconciledState.NOT_RECONCILED
                    ? Boolean.FALSE.toString()
                    : Boolean.TRUE.toString();

            writer.printRecord(account.getName(), transaction.getNumber(), debit, credit, balance, date,
                    timeStamp, transaction.getMemo(), transaction.getPayee(), reconciled);
        }
    } catch (final IOException e) {
        Logger.getLogger(CsvExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:sample.formatter.LocalDateTimeFormatter.java

@Override
public String print(LocalDateTime temporal, Locale locale) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    return formatter.format(temporal);
}

From source file:org.openlmis.fulfillment.web.util.StatusChangeDto.java

/**
 * Print createdDate for display purposes.
 * @return created date/*from   ww w . ja v  a2s.c  om*/
 */
@JsonIgnore
public String printDate() {
    Locale locale = LocaleContextHolder.getLocale();
    String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM,
            FormatStyle.MEDIUM, Chronology.ofLocale(locale), locale);
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(datePattern);

    return dateTimeFormatter.format(createdDate);
}

From source file:Graphite.java

private String getDateAsString(long start) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm_yyyyMMdd").withZone(zoneId);
    return formatter.format(Instant.ofEpochMilli(start));
}

From source file:de.bytefish.fcmjava.client.tests.interceptors.response.utils.RetryHeaderUtilsTest.java

@Test
public void headerFoundWithDateTimeInFutureContentTest() {

    // We assume the HTTP Header to contain an RFC1123-compliant DateTime value:
    DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;

    String formattedStringInFuture = formatter.format(DateUtils.getUtcNow().plusYears(1));

    // Expectations
    when(headerMock.getValue()).thenReturn(formattedStringInFuture);

    when(httpResponseMock.getFirstHeader("Retry-After")).thenReturn(headerMock);

    // Holds the Result:
    OutParameter<Duration> result = new OutParameter<Duration>();

    // Try to get the Result:
    boolean success = RetryHeaderUtils.tryDetermineRetryDelay(httpResponseMock, result);

    // Assertions:
    Assert.assertEquals(true, success);/*from   w  w  w.j ava  2s  .  c o m*/
    Assert.assertNotEquals(0, result.get().getSeconds());
    Assert.assertTrue(result.get().getSeconds() > 120);
}

From source file:de.bytefish.fcmjava.client.tests.http.apache.utils.RetryHeaderUtilsTest.java

@Test
public void headerFoundWithDateTimeInFutureContentTest() {

    // We assume the HTTP Header to contain an RFC1123-compliant DateTime value:
    DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;

    String formattedStringInFuture = formatter.format(DateUtils.getUtcNow().plusYears(1));

    // Expectations
    when(headerMock.getValue()).thenReturn(formattedStringInFuture);

    when(httpResponseMock.getFirstHeader("Retry-After")).thenReturn(headerMock);

    // Holds the Result:
    OutParameter<Duration> result = new OutParameter<>();

    // Try to get the Result:
    boolean success = RetryHeaderUtils.tryDetermineRetryDelay(httpResponseMock, result);

    // Assertions:
    Assert.assertEquals(true, success);/* ww  w.j ava 2  s.  c  o m*/
    Assert.assertNotEquals(0, result.get().getSeconds());
    Assert.assertTrue(result.get().getSeconds() > 120);
}

From source file:RequestStat.java

private String getDateFromInstant(long start) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd " + "HH:mm:ss")
            .withZone(ZoneId.systemDefault());
    return formatter.format(Instant.ofEpochMilli(start));
}