Example usage for java.time.format DateTimeFormatterBuilder DateTimeFormatterBuilder

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

Introduction

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

Prototype

public DateTimeFormatterBuilder() 

Source Link

Document

Constructs a new instance of the builder.

Usage

From source file:Main.java

public static void main(String[] args) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendValue(ChronoField.HOUR_OF_DAY)
            .appendLiteral(":").appendValue(ChronoField.MINUTE_OF_HOUR).toFormatter();

    System.out.println(formatter.format(LocalDateTime.now()));
}

From source file:Main.java

public static void main(String[] args) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendLiteral("New Year in ")
            .appendValue(ChronoField.YEAR).appendLiteral(" is  on  ")
            .appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL_STANDALONE).toFormatter();
    LocalDate ld = LocalDate.of(2014, Month.JANUARY, 1);
    String str = ld.format(formatter);
    System.out.println(str);//from ww  w  .  ja  v a2  s . co  m

}

From source file:Main.java

public static void main(String[] args) {
    Instant instant = Instant.parse("2014-07-16T10:15:30.00Z");
    LocalDate localDate = LocalDate.parse("2014-07-16", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    LocalDate localDate2 = LocalDate.parse("2014-07-16", DateTimeFormatter.ISO_LOCAL_DATE);

    DateTimeFormatter strangeFormat = new DateTimeFormatterBuilder().appendValue(MONTH_OF_YEAR, 2)
            .appendLiteral("==").appendValue(YEAR, 4).appendLiteral("--").appendValue(DAY_OF_MONTH, 2)
            .toFormatter();/*from  www .j a  va  2 s .c  o  m*/

    LocalDate localDate3 = LocalDate.parse("07==2014--16", strangeFormat);

    System.out.println(instant);
    System.out.println(localDate);
    System.out.println(localDate2);
    System.out.println(localDate3);

    LocalDate date = Year.of(2014).atMonth(7).atDay(16);
    String strangeDateFormat = date.format(strangeFormat);

    System.out.println(strangeDateFormat);
}

From source file:com.microsoft.sqlserver.testframework.sqlType.SqlTime.java

public SqlTime() {
    super("time", JDBCType.TIME, null, null);
    type = java.sql.Time.class;
    try {/* w  w w  . j a  v  a  2  s  .co m*/
        minvalue = new Time(dateFormat.parse((String) SqlTypeValue.TIME.minValue).getTime());
        maxvalue = new Time(dateFormat.parse((String) SqlTypeValue.TIME.maxValue).getTime());
    } catch (ParseException ex) {
        fail(ex.getMessage());
    }
    this.precision = 7;
    this.variableLengthType = VariableLengthType.Precision;
    generatePrecision();
    formatter = new DateTimeFormatterBuilder().appendPattern(basePattern)
            .appendFraction(ChronoField.NANO_OF_SECOND, 0, this.precision, true).toFormatter();

}

From source file:com.microsoft.sqlserver.testframework.sqlType.SqlDateTime2.java

public SqlDateTime2() {
    super("datetime2", JDBCType.TIMESTAMP, null, null);
    try {//from  w  w  w  .j a v a 2s. c  o  m
        minvalue = new Timestamp(dateFormat.parse((String) SqlTypeValue.DATETIME2.minValue).getTime());
        maxvalue = new Timestamp(dateFormat.parse((String) SqlTypeValue.DATETIME2.maxValue).getTime());
    } catch (ParseException ex) {
        fail(ex.getMessage());
    }
    this.precision = 7;
    this.variableLengthType = VariableLengthType.Precision;
    generatePrecision();
    formatter = new DateTimeFormatterBuilder().appendPattern(basePattern)
            .appendFraction(ChronoField.NANO_OF_SECOND, 0, this.precision, true).toFormatter();

}

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. ja  va2s. c o  m

        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:Main.java

/**
 * Parses a String to a ChronoLocalDate using a DateTimeFormatter with a short
 * pattern based on the current Locale and the provided Chronology, then
 * converts this to a LocalDate (ISO) value.
 *
 * @param text/*from w  ww .j  ava  2  s. co  m*/
 *          - the input date text in the SHORT format expected for the
 *          Chronology and the current Locale.
 *
 * @param chrono
 *          - an optional Chronology. If null, then IsoChronology is used.
 */
public static LocalDate fromString(String text, Chronology chrono) {
    if (text != null && !text.isEmpty()) {
        Locale locale = Locale.getDefault(Locale.Category.FORMAT);
        if (chrono == null) {
            chrono = IsoChronology.INSTANCE;
        }
        String pattern = "M/d/yyyy GGGGG";
        DateTimeFormatter df = new DateTimeFormatterBuilder().parseLenient().appendPattern(pattern)
                .toFormatter().withChronology(chrono).withDecimalStyle(DecimalStyle.of(locale));
        TemporalAccessor temporal = df.parse(text);
        ChronoLocalDate cDate = chrono.date(temporal);
        return LocalDate.from(cDate);
    }
    return null;
}

From source file:org.apache.metron.profiler.spark.TimestampParser.java

/**
 * Parses an input string and returns an optional timestamp in epoch milliseconds.
 *
 * @param inputString The input defining a timestamp.
 * @return A timestamp in epoch milliseconds.
 *///  w  ww.  jav a  2 s  . c o m
public Optional<Long> parse(String inputString) {
    Optional<Long> epochMilli = Optional.empty();

    // a blank is acceptable and treated as undefined
    if (StringUtils.isNotBlank(inputString)) {
        epochMilli = Optional.of(new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_INSTANT)
                .toFormatter().parse(inputString, Instant::from).toEpochMilli());
    }

    return epochMilli;
}

From source file:org.opensingular.form.type.util.STypeYearMonth.java

private static DateTimeFormatter formatter() {
    return new DateTimeFormatterBuilder().appendPattern("MM/yyyy").toFormatter();
}

From source file:org.talend.dataprep.transformation.actions.date.DateParser.java

/**
 * Parse the date from the given patterns.
 *
 * @param value the text to parse./*from www  .jav  a  2 s  .  com*/
 * @param patterns the patterns to use.
 * @return the parsed date-time
 */
public LocalDateTime parseDateFromPatterns(String value, List<DatePattern> patterns) {

    // take care of the null value
    if (value == null) {
        throw new DateTimeException("cannot parse null");
    }

    for (DatePattern pattern : patterns) {
        final DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive()
                .append(pattern.getFormatter()).toFormatter(Locale.ENGLISH);

        // first try to parse directly as LocalDateTime
        try {
            return LocalDateTime.parse(value, formatter);
        } catch (DateTimeException e) {
            LOGGER.trace("Unable to parse date '{}' using LocalDateTime.", value, e);
            // if it fails, let's try the LocalDate first
            try {
                LocalDate temp = LocalDate.parse(value, formatter);
                return temp.atStartOfDay();
            } catch (DateTimeException e2) {
                LOGGER.trace("Unable to parse date '{}' using LocalDate.", value, e2);
                // nothing to do here, just try the next formatter
            }
        }
    }
    throw new DateTimeException("'" + value + "' does not match any known pattern");
}