Example usage for java.time.format DateTimeFormatter ISO_LOCAL_DATE_TIME

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

Introduction

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

Prototype

DateTimeFormatter ISO_LOCAL_DATE_TIME

To view the source code for java.time.format DateTimeFormatter ISO_LOCAL_DATE_TIME.

Click Source Link

Document

The ISO date-time formatter that formats or parses a date-time without an offset, such as '2011-12-03T10:15:30'.

Usage

From source file:net.morimekta.idltool.IdlUtils.java

public static String formatAgo(long timestamp) {
    Instant instant = Instant.ofEpochSecond(timestamp / 1000);
    LocalDateTime local = instant.atZone(Clock.systemUTC().getZone())
            .withZoneSameInstant(Clock.systemDefaultZone().getZone()).toLocalDateTime();
    return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(local).replaceAll("[T]", " ");
}

From source file:com.tascape.reactor.report.MySqlBaseBean.java

public static long getMillis(String time) {
    if (time == null || time.trim().isEmpty()) {
        return System.currentTimeMillis();
    } else {//  w ww . j  ava  2 s  .  co  m
        LocalDateTime ldt = LocalDateTime.parse(time, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        LOG.trace("ldt {}", ldt);
        ZoneId zone = ZoneId.of("America/Los_Angeles");
        ldt.atZone(zone);
        LOG.trace("ldt {}", ldt);
        return ldt.toInstant(ZoneOffset.ofHours(-8)).toEpochMilli();
    }
}

From source file:net.tradelib.core.Series.java

static public Series fromCsv(String path, boolean header, DateTimeFormatter dtf, LocalTime lt)
        throws Exception {

    if (dtf == null) {
        if (lt == null)
            dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        else/*w w  w. j a  v  a  2 s .  c  om*/
            dtf = DateTimeFormatter.ISO_DATE;
    }

    // Parse and import the csv
    CSVFormat csvFmt = CSVFormat.DEFAULT.withCommentMarker('#').withIgnoreSurroundingSpaces();
    if (header)
        csvFmt = csvFmt.withHeader();
    CSVParser csv = csvFmt.parse(new BufferedReader(new FileReader(path)));

    int ncols = -1;
    Series result = null;
    double[] values = null;

    for (CSVRecord rec : csv.getRecords()) {
        if (result == null) {
            ncols = rec.size() - 1;
            values = new double[ncols];
            result = new Series(ncols);
        }

        for (int ii = 0; ii < ncols; ++ii) {
            values[ii] = Double.parseDouble(rec.get(ii + 1));
        }

        LocalDateTime ldt;
        if (lt != null) {
            ldt = LocalDate.parse(rec.get(0), dtf).atTime(lt);
        } else {
            ldt = LocalDateTime.parse(rec.get(0), dtf);
        }

        result.append(ldt, values);
    }

    if (header) {
        Map<String, Integer> headerMap = csv.getHeaderMap();
        result.clearNames();
        for (Map.Entry<String, Integer> me : headerMap.entrySet()) {
            if (me.getValue() > 0)
                result.setName(me.getKey(), me.getValue() - 1);
        }
    }

    return result;
}

From source file:net.tradelib.core.Series.java

public void print() {
    print(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}

From source file:org.apache.nifi.processors.solr.SolrUtils.java

private static void writeValue(final SolrInputDocument inputDocument, final Object value,
        final String fieldName, final DataType dataType, final List<String> fieldsToIndex) throws IOException {
    final DataType chosenDataType = dataType.getFieldType() == RecordFieldType.CHOICE
            ? DataTypeUtils.chooseDataType(value, (ChoiceDataType) dataType)
            : dataType;//from   w ww.j a  v a2 s  .  c o  m
    final Object coercedValue = DataTypeUtils.convertType(value, chosenDataType, fieldName);
    if (coercedValue == null) {
        return;
    }

    switch (chosenDataType.getFieldType()) {
    case DATE: {
        final String stringValue = DataTypeUtils.toString(coercedValue,
                () -> DataTypeUtils.getDateFormat(RecordFieldType.DATE.getDefaultFormat()));
        if (DataTypeUtils.isLongTypeCompatible(stringValue)) {
            LocalDate localDate = getLocalDateFromEpochTime(fieldName, coercedValue);
            addFieldToSolrDocument(inputDocument, fieldName,
                    localDate.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z', fieldsToIndex);
        } else {
            addFieldToSolrDocument(inputDocument, fieldName,
                    LocalDate.parse(stringValue).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z',
                    fieldsToIndex);
        }
        break;
    }
    case TIMESTAMP: {
        final String stringValue = DataTypeUtils.toString(coercedValue,
                () -> DataTypeUtils.getDateFormat(RecordFieldType.TIMESTAMP.getDefaultFormat()));
        if (DataTypeUtils.isLongTypeCompatible(stringValue)) {
            LocalDateTime localDateTime = getLocalDateTimeFromEpochTime(fieldName, coercedValue);
            addFieldToSolrDocument(inputDocument, fieldName,
                    localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z', fieldsToIndex);
        } else {
            addFieldToSolrDocument(inputDocument, fieldName,
                    LocalDateTime.parse(stringValue).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z',
                    fieldsToIndex);
        }
        break;
    }
    case DOUBLE:
        addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toDouble(coercedValue, fieldName),
                fieldsToIndex);
        break;
    case FLOAT:
        addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toFloat(coercedValue, fieldName),
                fieldsToIndex);
        break;
    case LONG:
        addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toLong(coercedValue, fieldName),
                fieldsToIndex);
        break;
    case INT:
    case BYTE:
    case SHORT:
        addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toInteger(coercedValue, fieldName),
                fieldsToIndex);
        break;
    case CHAR:
    case STRING:
        addFieldToSolrDocument(inputDocument, fieldName, coercedValue.toString(), fieldsToIndex);
        break;
    case BIGINT:
        if (coercedValue instanceof Long) {
            addFieldToSolrDocument(inputDocument, fieldName, (Long) coercedValue, fieldsToIndex);
        } else {
            addFieldToSolrDocument(inputDocument, fieldName, (BigInteger) coercedValue, fieldsToIndex);
        }
        break;
    case BOOLEAN:
        final String stringValue = coercedValue.toString();
        if ("true".equalsIgnoreCase(stringValue)) {
            addFieldToSolrDocument(inputDocument, fieldName, true, fieldsToIndex);
        } else if ("false".equalsIgnoreCase(stringValue)) {
            addFieldToSolrDocument(inputDocument, fieldName, false, fieldsToIndex);
        } else {
            addFieldToSolrDocument(inputDocument, fieldName, stringValue, fieldsToIndex);
        }
        break;
    case RECORD: {
        final Record record = (Record) coercedValue;
        writeRecord(record, inputDocument, fieldsToIndex, fieldName);
        break;
    }
    case ARRAY:
    default:
        if (coercedValue instanceof Object[]) {
            final Object[] values = (Object[]) coercedValue;
            for (Object element : values) {
                if (element instanceof Record) {
                    writeRecord((Record) element, inputDocument, fieldsToIndex, fieldName);
                } else {
                    addFieldToSolrDocument(inputDocument, fieldName, coercedValue.toString(), fieldsToIndex);
                }
            }
        } else {
            addFieldToSolrDocument(inputDocument, fieldName, coercedValue.toString(), fieldsToIndex);
        }
        break;
    }
}

From source file:org.dhatim.fastexcel.Correctness.java

@Test
public void singleWorksheet() throws Exception {
    String sheetName = "Worksheet 1";
    String stringValue = "Sample text with chars to escape : < > & \\ \" ' ~        ";
    Date dateValue = new Date();
    LocalDateTime localDateTimeValue = LocalDateTime.now();
    ZoneId timezone = ZoneId.of("Australia/Sydney");
    ZonedDateTime zonedDateValue = ZonedDateTime.ofInstant(dateValue.toInstant(), timezone);
    double doubleValue = 1.234;
    int intValue = 2_016;
    long longValue = 2_016_000_000_000L;
    BigDecimal bigDecimalValue = BigDecimal.TEN;
    byte[] data = writeWorkbook(wb -> {
        Worksheet ws = wb.newWorksheet(sheetName);
        int i = 1;
        ws.value(i, i++, stringValue);/*from  ww  w  .  j a  v  a  2 s.c o m*/
        ws.value(i, i++, dateValue);
        ws.value(i, i++, localDateTimeValue);
        ws.value(i, i++, zonedDateValue);
        ws.value(i, i++, doubleValue);
        ws.value(i, i++, intValue);
        ws.value(i, i++, longValue);
        ws.value(i, i++, bigDecimalValue);
        try {
            ws.finish();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    // Check generated workbook with Apache POI
    XSSFWorkbook xwb = new XSSFWorkbook(new ByteArrayInputStream(data));
    assertThat(xwb.getActiveSheetIndex()).isEqualTo(0);
    assertThat(xwb.getNumberOfSheets()).isEqualTo(1);
    XSSFSheet xws = xwb.getSheet(sheetName);
    @SuppressWarnings("unchecked")
    Comparable<XSSFRow> row = (Comparable) xws.getRow(0);
    assertThat(row).isNull();
    int i = 1;
    assertThat(xws.getRow(i).getCell(i++).getStringCellValue()).isEqualTo(stringValue);
    assertThat(xws.getRow(i).getCell(i++).getDateCellValue()).isEqualTo(dateValue);
    // Check zoned timestamps have the same textual representation as the Dates extracted from the workbook
    // (Excel date serial numbers do not carry timezone information)
    assertThat(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime
            .ofInstant(xws.getRow(i).getCell(i++).getDateCellValue().toInstant(), ZoneId.systemDefault())))
                    .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTimeValue));
    assertThat(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime
            .ofInstant(xws.getRow(i).getCell(i++).getDateCellValue().toInstant(), ZoneId.systemDefault())))
                    .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(zonedDateValue));
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(doubleValue);
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(intValue);
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(longValue);
    assertThat(new BigDecimal(xws.getRow(i).getCell(i++).getRawValue())).isEqualTo(bigDecimalValue);
}

From source file:org.openhab.binding.darksky.internal.handler.DarkSkyWeatherAndForecastHandler.java

/**
 * Applies the given configuration to the given timestamp.
 *
 * @param dateTime timestamp represented as {@link ZonedDateTime}
 * @param config {@link DarkSkyChannelConfiguration} instance
 * @return the modified timestamp//from ww w .ja  va  2 s.c o m
 */
private ZonedDateTime applyChannelConfig(ZonedDateTime dateTime, @Nullable DarkSkyChannelConfiguration config) {
    ZonedDateTime modifiedDateTime = dateTime;
    if (config != null) {
        if (config.getOffset() != 0) {
            if (logger.isTraceEnabled()) {
                logger.trace("Apply offset of {} min to timestamp '{}'.", config.getOffset(),
                        modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            }
            modifiedDateTime = modifiedDateTime.plusMinutes(config.getOffset());
        }
        long earliestInMinutes = config.getEarliestInMinutes();
        if (earliestInMinutes > 0) {
            ZonedDateTime earliestDateTime = modifiedDateTime.truncatedTo(ChronoUnit.DAYS)
                    .plusMinutes(earliestInMinutes);
            if (modifiedDateTime.isBefore(earliestDateTime)) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Use earliest timestamp '{}' instead of '{}'.",
                            earliestDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
                            modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                return earliestDateTime;
            }
        }
        long latestInMinutes = config.getLatestInMinutes();
        if (latestInMinutes > 0) {
            ZonedDateTime latestDateTime = modifiedDateTime.truncatedTo(ChronoUnit.DAYS)
                    .plusMinutes(latestInMinutes);
            if (modifiedDateTime.isAfter(latestDateTime)) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Use latest timestamp '{}' instead of '{}'.",
                            latestDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
                            modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                return latestDateTime;
            }
        }
    }
    return modifiedDateTime;
}

From source file:org.openhab.binding.darksky.internal.handler.DarkSkyWeatherAndForecastHandler.java

/**
 * Schedules or reschedules a job for the channel with the given id if the given timestamp is in the future.
 *
 * @param channelId id of the channel//from   w w w .  j  a v a 2s .c  o m
 * @param dateTime timestamp of the job represented as {@link ZonedDateTime}
 */
@SuppressWarnings("null")
private synchronized void scheduleJob(String channelId, ZonedDateTime dateTime) {
    long delay = dateTime.toEpochSecond() - ZonedDateTime.now().toEpochSecond();
    if (delay > 0) {
        Job job = JOBS.get(channelId);
        if (job == null || job.getFuture().isCancelled()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Schedule job for '{}' in {} s (at '{}').", channelId, delay,
                        dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            }
            JOBS.put(channelId, new Job(channelId, delay));
        } else {
            if (delay != job.getDelay()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Reschedule job for '{}' in {} s (at '{}').", channelId, delay,
                            dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                job.getFuture().cancel(true);
                JOBS.put(channelId, new Job(channelId, delay));
            }
        }
    }
}

From source file:org.talend.dataquality.statistics.datetime.utils.PatternListGenerator.java

@SuppressWarnings("unused")
private static void validateISOPattens(List<String> isoPatternList) {

    Set<String> formattedDateTimeSet = new HashSet<String>();
    for (String pattern : isoPatternList) {
        formattedDateTimeSet.add(getFormattedDateTime(pattern, Locale.US));
    }//  ww  w.  j  a  v a 2  s .com

    DateTimeFormatter[] formatters = new DateTimeFormatter[] { DateTimeFormatter.BASIC_ISO_DATE, // 1
            DateTimeFormatter.ISO_DATE, // 2
            DateTimeFormatter.ISO_DATE_TIME, // 3
            // DateTimeFormatter.ISO_TIME, //
            DateTimeFormatter.ISO_INSTANT, // 4
            DateTimeFormatter.ISO_LOCAL_DATE, // 5
            DateTimeFormatter.ISO_LOCAL_DATE_TIME, // 6
            // DateTimeFormatter.ISO_LOCAL_TIME, //
            DateTimeFormatter.ISO_OFFSET_DATE, // 7
            DateTimeFormatter.ISO_OFFSET_DATE_TIME, // 8
            // DateTimeFormatter.ISO_OFFSET_TIME, //
            DateTimeFormatter.ISO_ORDINAL_DATE, // 9
            DateTimeFormatter.ISO_WEEK_DATE, // 10
            DateTimeFormatter.ISO_ZONED_DATE_TIME, // 11
            DateTimeFormatter.RFC_1123_DATE_TIME, // 12
    };

    System.out.println("-------------Validate ISO PattenText-------------");
    for (int i = 0; i < formatters.length; i++) {

        System.out.print((i + 1) + "\t");
        try {
            String formattedDateTime = ZONED_DATE_TIME.format(formatters[i]);
            System.out.print(formattedDateTimeSet.contains(formattedDateTime) ? "YES\t" : "NO\t");
            System.out.println(formattedDateTime);
        } catch (Throwable t) {
            System.out.println(t.getMessage());
        }
    }

}

From source file:uk.q3c.krail.i18n.ClassBundleWriter.java

@Override
public void setBundle(EnumResourceBundle<E> bundle) {
    super.setBundle(bundle);
    this.clazz = bundle.getClass();
    this.keyClass = bundle.getKeyClass();
    this.superClass = clazz.getSuperclass();
    this.entryMap = bundle.getMap();
    this.pkg = ClassUtils.getPackageCanonicalName(clazz);
    classJavaDoc = "Generated by Krail " + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}