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:org.apache.geode.management.internal.cli.commands.ExportLogsDUnitTest.java

@Test
public void testExportWithStartAndEndDateTimeFiltering() throws Exception {
    ZonedDateTime cutoffTime = LocalDateTime.now().atZone(ZoneId.systemDefault());

    String messageAfterCutoffTime = "[this message should not show up since it is after cutoffTime]";
    LogLine logLineAfterCutoffTime = new LogLine(messageAfterCutoffTime, "info", true);
    server1.invoke(() -> {//ww  w  .  j  a  v a2 s.  c  o  m
        Logger logger = LogService.getLogger();
        logLineAfterCutoffTime.writeLog(logger);
    });

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(FORMAT);
    String cutoffTimeString = dateTimeFormatter.format(cutoffTime);

    CommandStringBuilder commandStringBuilder = new CommandStringBuilder("export logs");
    commandStringBuilder.addOption("start-time", dateTimeFormatter.format(cutoffTime.minusDays(1)));
    commandStringBuilder.addOption("end-time", cutoffTimeString);
    commandStringBuilder.addOption("log-level", "debug");

    gfshConnector.executeAndVerifyCommand(commandStringBuilder.toString());

    expectedMessages.get(server1).add(logLineAfterCutoffTime);
    Set<String> acceptedLogLevels = Stream.of("info", "error", "debug").collect(toSet());
    verifyZipFileContents(acceptedLogLevels);
}

From source file:rjc.jplanner.model.DateTime.java

/****************************************** toString *******************************************/
public String toString(String format) {
    // convert to string in specified format
    LocalDateTime ldt = LocalDateTime.ofEpochSecond(m_milliseconds / 1000L,
            (int) (m_milliseconds % 1000 * 1000000), ZoneOffset.UTC);

    // to support half-of-year using Bs, quote any unquoted Bs in format
    StringBuilder newFormat = new StringBuilder();
    boolean inQuote = false;
    boolean inB = false;
    char here;/*from  w ww. j  a  v  a  2  s .  com*/
    for (int i = 0; i < format.length(); i++) {
        here = format.charAt(i);

        // are we in quoted text?
        if (here == QUOTE)
            inQuote = !inQuote;

        // replace unquoted Bs with special code
        if (inB && here == CHARB) {
            newFormat.append(CODE);
            continue;
        }

        // come to end of unquoted Bs
        if (inB && here != CHARB) {
            newFormat.append(QUOTE);
            inB = false;
            inQuote = false;
        }

        // start of unquoted Bs, start quote with special code
        if (!inQuote && here == CHARB) {
            // avoid creating double quotes
            if (newFormat.length() > 0 && newFormat.charAt(newFormat.length() - 1) == QUOTE) {
                newFormat.deleteCharAt(newFormat.length() - 1);
                newFormat.append(CODE);
            } else
                newFormat.append("'" + CODE);
            inQuote = true;
            inB = true;
        } else {
            newFormat.append(here);
        }
    }

    // close quote if quote still open
    if (inQuote)
        newFormat.append(QUOTE);

    String str = ldt.format(DateTimeFormatter.ofPattern(newFormat.toString()));

    // no special code so can return string immediately
    if (!str.contains(CODE))
        return str;

    // determine half-of-year
    String yearHalf;
    if (month() < 7)
        yearHalf = "1";
    else
        yearHalf = "2";

    // four or more Bs is not allowed
    String Bs = StringUtils.repeat(CODE, 4);
    if (str.contains(Bs))
        throw new IllegalArgumentException("Too many pattern letters: B");

    // replace three Bs
    Bs = StringUtils.repeat(CODE, 3);
    if (yearHalf.equals("1"))
        str = str.replace(Bs, yearHalf + "st half");
    else
        str = str.replace(Bs, yearHalf + "nd half");

    // replace two Bs
    Bs = StringUtils.repeat(CODE, 2);
    str = str.replace(Bs, "H" + yearHalf);

    // replace one Bs
    Bs = StringUtils.repeat(CODE, 1);
    str = str.replace(Bs, yearHalf);

    return str;
}

From source file:org.geoserver.qos.BaseQosXmlEncoder.java

public void encodeOperatingInfoTime(String tag, Translator tx, OperatingInfoTime otime) {
    tx.start(tag);//from w w w  .  j av a2  s  .c  o m
    // <qos:On>
    if (otime.getDays() != null && !otime.getDays().isEmpty()) {
        final String onTag = QosSchema.QOS_PREFIX + ":" + ON_TAG;
        tx.start(onTag);
        // days concatenation, with spaces
        StringBuilder ob = new StringBuilder();
        otime.getDays().forEach(d -> {
            ob.append(d.value());
            ob.append(" ");
        });
        tx.chars(ob.toString().trim());
        tx.end(onTag);
    }
    // <qos:StartTime>10:00:00+03:00</qos:StartTime>
    if (otime.getStartTime() != null) {
        final String startTimeTag = QosSchema.QOS_PREFIX + ":StartTime";
        tx.start(startTimeTag);
        tx.chars(otime.getStartTime().format(DateTimeFormatter.ofPattern(OperatingInfoTime.TIME_PATTERN)));
        tx.end(startTimeTag);
    }

    // <qos:EndTime>14:59:59+03:00</qos:EndTime>
    if (otime.getEndTime() != null) {
        final String endTimeTag = QosSchema.QOS_PREFIX + ":EndTime";
        tx.start(endTimeTag);
        tx.chars(otime.getEndTime().format(DateTimeFormatter.ofPattern(OperatingInfoTime.TIME_PATTERN)));
        tx.end(endTimeTag);
    }

    // end main tag
    tx.end(tag);
}

From source file:com.synopsys.integration.blackduck.codelocation.signaturescanner.command.ScanPathsUtility.java

public File createSpecificRunOutputDirectory(final File generalOutputDirectory)
        throws BlackDuckIntegrationException {
    final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss-SSS")
            .withZone(ZoneOffset.UTC);
    final String timeStringPrefix = Instant.now().atZone(ZoneOffset.UTC).format(dateTimeFormatter);

    final int uniqueThreadIdSuffix = defaultMultiThreadingId.incrementAndGet();
    return createRunOutputDirectory(generalOutputDirectory, timeStringPrefix,
            Integer.toString(uniqueThreadIdSuffix));
}

From source file:org.thingsboard.server.dao.audit.sink.ElasticsearchAuditLogSink.java

private String getIndexName(TenantId tenantId) {
    String indexName = indexPattern;
    if (indexName.contains(TENANT_PLACEHOLDER) && tenantId != null) {
        indexName = indexName.replace(TENANT_PLACEHOLDER, tenantId.getId().toString());
    }//from ww  w.  ja  v  a2  s  .c o m
    if (indexName.contains(DATE_PLACEHOLDER)) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
        indexName = indexName.replace(DATE_PLACEHOLDER, now.format(formatter));
    }
    return indexName.toLowerCase();
}

From source file:aajavafx.Schedule1Controller.java

@Override
public void initialize(URL url, ResourceBundle rb) {
    schIdColumn.setCellValueFactory(cellData -> cellData.getValue().schIdProperty().asObject());
    schDateColumn.setCellValueFactory(cellData -> cellData.getValue().schDateProperty());
    schFromTimeColumn.setCellValueFactory(cellData -> cellData.getValue().schFromTimeProperty());
    schUntilTimeColumn.setCellValueFactory(cellData -> cellData.getValue().schUntilTimeProperty());
    emplVisitedCustColumn//from  w  ww .ja v a 2s . c  o m
            .setCellValueFactory(cellData -> cellData.getValue().emplVisitedCustProperty().asObject());
    customersCuIdColumn.setCellValueFactory(cellData -> cellData.getValue().customersCuIdProperty());
    employeesEmpIdColumn.setCellValueFactory(cellData -> cellData.getValue().employeesEmpIdProperty());

    empIdColumn.setCellValueFactory(cellData -> cellData.getValue().idProperty().asObject());
    empFirstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNProperty());
    empLastColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
    empUserNameColumn.setCellValueFactory(cellData -> cellData.getValue().empUserNameProperty());

    cuIdColumn.setCellValueFactory(cellData -> cellData.getValue().customerIdProperty().asObject());
    cuFirstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
    cuLastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
    cuPersonnumerColumn.setCellValueFactory(cellData -> cellData.getValue().personnumerProperty());

    pickADate.setValue(LocalDate.now());
    pickADate.setOnAction(new EventHandler() {
        public void handle(Event t) {
            LocalDate date = pickADate.getValue();
            System.err.println("Selected date: " + date);
            setDate(pickADate.getValue().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            System.out.println("Date now: " + getDate());

        }

    });

    try {

        tableEmployee.setItems(getEmployee());
        tableCustomer.setItems(getCustomer());
        tableSchedule.setItems(getSchedule());
    } catch (IOException ex) {
        Logger.getLogger(EmployeeController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(EmployeeController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.openhab.binding.ntp.internal.handler.NtpHandler.java

@Override
public void initialize() {
    try {/*from   ww w.j a v a2  s .  c  om*/
        logger.debug("Initializing NTP handler for '{}'.", getThing().getUID());

        Configuration config = getThing().getConfiguration();
        hostname = config.get(PROPERTY_NTP_SERVER_HOST).toString();
        port = (BigDecimal) config.get(PROPERTY_NTP_SERVER_PORT);
        refreshInterval = (BigDecimal) config.get(PROPERTY_REFRESH_INTERVAL);
        refreshNtp = (BigDecimal) config.get(PROPERTY_REFRESH_NTP);
        refreshNtpCount = 0;

        try {
            Object timeZoneConfigValue = config.get(PROPERTY_TIMEZONE);
            if (timeZoneConfigValue != null) {
                timeZone = TimeZone.getTimeZone(timeZoneConfigValue.toString());
            } else {
                timeZone = TimeZone.getDefault();
                logger.debug("{} using default TZ '{}', because configuration property '{}' is null.",
                        getThing().getUID(), timeZone, PROPERTY_TIMEZONE);
            }
        } catch (Exception e) {
            timeZone = TimeZone.getDefault();
            logger.debug("{} using default TZ '{}' due to an occurred exception: ", getThing().getUID(),
                    timeZone, e);
        }

        try {
            Object localeStringConfigValue = config.get(PROPERTY_LOCALE);
            if (localeStringConfigValue != null) {
                locale = new Locale(localeStringConfigValue.toString());
            } else {
                locale = localeProvider.getLocale();
                logger.debug("{} using default locale '{}', because configuration property '{}' is null.",
                        getThing().getUID(), locale, PROPERTY_LOCALE);
            }
        } catch (Exception e) {
            locale = localeProvider.getLocale();
            logger.debug("{} using default locale '{}' due to an occurred exception: ", getThing().getUID(),
                    locale, e);
        }
        dateTimeChannelUID = new ChannelUID(getThing().getUID(), CHANNEL_DATE_TIME);
        stringChannelUID = new ChannelUID(getThing().getUID(), CHANNEL_STRING);
        try {
            Channel stringChannel = getThing().getChannel(stringChannelUID.getId());
            if (stringChannel != null) {
                Configuration cfg = stringChannel.getConfiguration();
                String dateTimeFormatString = cfg.get(PROPERTY_DATE_TIME_FORMAT).toString();
                if (!(dateTimeFormatString == null || dateTimeFormatString.isEmpty())) {
                    dateTimeFormat = DateTimeFormatter.ofPattern(dateTimeFormatString);
                } else {
                    logger.debug("No format set in channel config for {}. Using default format.",
                            stringChannelUID);
                    dateTimeFormat = DateTimeFormatter.ofPattern(DATE_PATTERN_WITH_TZ);
                }
            } else {
                logger.debug("Missing channel: '{}'", stringChannelUID.getId());
            }
        } catch (RuntimeException ex) {
            logger.debug("No channel config or invalid format for {}. Using default format. ({})",
                    stringChannelUID, ex.getMessage());
            dateTimeFormat = DateTimeFormatter.ofPattern(DATE_PATTERN_WITH_TZ);
        }
        SDF.setTimeZone(timeZone);
        dateTimeFormat.withZone(timeZone.toZoneId());

        logger.debug(
                "Initialized NTP handler '{}' with configuration: host '{}', refresh interval {}, timezone {}, locale {}.",
                getThing().getUID(), hostname, refreshInterval, timeZone, locale);
        startAutomaticRefresh();
    } catch (Exception ex) {
        logger.error("Error occurred while initializing NTP handler: {}", ex.getMessage(), ex);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                "@text/offline.conf-error-init-handler");
    }
}

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

/**
 * Retrieve the exact string retrieved from the api response that 
 * represents a date.//from   w  w w  .  j a  v a  2  s  .c  o m
 * @param pattern DateTimeFormatter pattern to use for ofPattern()
 * @return date string 
 */
@Override
public String getDateString(final String pattern) {
    return date.format(DateTimeFormatter.ofPattern(pattern));
}

From source file:com.haulmont.cuba.web.widgets.CubaTimeField.java

protected DateTimeFormatter getDateTimeFormatter() {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat);
    Locale locale = getLocale();//from  w w w .  j ava2s.  co m
    if (locale != null) {
        dateTimeFormatter = dateTimeFormatter.withLocale(locale);
    }
    return dateTimeFormatter;
}

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

public void importCsv(final Reader reader) {
    final CsvReader csvReader = new CsvReader(reader, new CsvConfig());
    final DateTimeFormatter formatter = DateTimeFormatter
            .ofPattern(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND);
    try {/*from ww  w  .j a v  a2s  . c  om*/
        List<String> list;
        csvReader.readValues(); // ignore header
        while ((list = csvReader.readValues()) != null) {
            try {
                final String sessionId = list.get(0);
                CrawlingSession crawlingSession = crawlingSessionBhv.selectEntity(cb -> {
                    cb.query().setSessionId_Equal(sessionId);
                    cb.specify().columnSessionId();
                }).orElse(null);//TODO
                if (crawlingSession == null) {
                    crawlingSession = new CrawlingSession();
                    crawlingSession.setSessionId(list.get(0));
                    crawlingSession.setCreatedTime(LocalDateTime.parse(list.get(1), formatter));
                    crawlingSessionBhv.insert(crawlingSession);
                }

                final CrawlingSessionInfo entity = new CrawlingSessionInfo();
                entity.setCrawlingSessionId(crawlingSession.getId());
                entity.setKey(list.get(2));
                entity.setValue(list.get(3));
                entity.setCreatedTime(LocalDateTime.parse(list.get(4), formatter));
                crawlingSessionInfoBhv.insert(entity);
            } catch (final Exception e) {
                log.warn("Failed to read a click log: " + list, e);
            }
        }
    } catch (final IOException e) {
        log.warn("Failed to read a click log.", e);
    }
}