Example usage for java.time.format DateTimeFormatter parse

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

Introduction

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

Prototype

public TemporalAccessor parse(CharSequence text) 

Source Link

Document

Fully parses the text producing a temporal object.

Usage

From source file:Main.java

public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    TemporalAccessor ta = formatter.parse("06/10/2014");
    LocalDate ld = LocalDate.from(ta);
    System.out.println(ld);/*from  w ww  . j ava2  s  .c  om*/

}

From source file:Main.java

public static void main(String[] args) {
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
    System.out.println(dateFormatter.format(LocalDate.now())); // Current Local Date
    System.out.println(dateFormatter.parse("Jan 19, 2014").getClass().getName()); //java.time.format.Parsed
    System.out.println(dateFormatter.parse("Jan 19, 2014", LocalDate::from)); // Jan 19, 2014

}

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//w  w w . j a v  a2  s. c  om
 *          - 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:com.buffalokiwi.api.APIDate.java

/**
 * Attempt to take some value and turn it into a valid APIDate.
 * If it isn't valid, then this returns null.
 * /*from w ww  .ja va2s.c  om*/
 * @param value Jet value 
 * @return date or null
 */
public static APIDate fromStringOrNull(String value) {
    if (value == null || value.isEmpty())
        return null;

    for (final DateTimeFormatter fmt : FORMATS) {
        try {
            final TemporalAccessor t = fmt.parse(value);

            try {
                return new APIDate(ZonedDateTime.from(t));
            } catch (DateTimeException e) {
                APILog.warn(LOG, e, "Failed to determine timezone.  Defaulting to local offset");
                final LocalDateTime local = LocalDateTime.from(t);
                final ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
                return new APIDate(ZonedDateTime.of(local, offset));
            }
        } catch (DateTimeParseException e) {
            //..do nothing, yet.
        }
    }

    //..Not found.  Log it and return null
    APILog.error(LOG, "Failed to parse date string:", value);
    return null;
}

From source file:msi.gama.util.GamaDate.java

private static Temporal parse(final IScope scope, final String original, final DateTimeFormatter df) {
    if (original == null || original.isEmpty() || original.equals("now")) {
        return LocalDateTime.now(GamaDateType.DEFAULT_ZONE);
    }/*from  w  w  w .j av a 2  s . c o m*/
    Temporal result = null;

    if (df != null) {
        try {
            final TemporalAccessor ta = df.parse(original);
            if (ta instanceof Temporal) {
                return (Temporal) ta;
            }
            if (!ta.isSupported(ChronoField.YEAR) && !ta.isSupported(ChronoField.MONTH_OF_YEAR)
                    && !ta.isSupported(ChronoField.DAY_OF_MONTH)) {
                if (ta.isSupported(ChronoField.HOUR_OF_DAY)) {
                    return LocalTime.from(ta);
                }
            }
            if (!ta.isSupported(ChronoField.HOUR_OF_DAY) && !ta.isSupported(ChronoField.MINUTE_OF_HOUR)
                    && !ta.isSupported(ChronoField.SECOND_OF_MINUTE)) {
                return LocalDate.from(ta);
            }
            return LocalDateTime.from(ta);
        } catch (final DateTimeParseException e) {
            e.printStackTrace();
        }
        GAMA.reportAndThrowIfNeeded(scope,
                GamaRuntimeException.warning(
                        "The date " + original + " can not correctly be parsed by the pattern provided", scope),
                false);
        return parse(scope, original, null);
    }

    String dateStr;
    try {
        // We first make sure all date fields have the correct length and
        // the string is correctly formatted
        String string = original;
        if (!original.contains("T") && original.contains(" ")) {
            string = StringUtils.replaceOnce(original, " ", "T");
        }
        final String[] base = string.split("T");
        final String[] date = base[0].split("-");
        String other;
        if (base.length == 1) {
            other = "00:00:00";
        } else {
            other = base[1];
        }
        String year, month, day;
        if (date.length == 1) {
            // ISO basic date format
            year = date[0].substring(0, 4);
            month = date[0].substring(4, 6);
            day = date[0].substring(6, 8);
        } else {
            year = date[0];
            month = date[1];
            day = date[2];
        }
        if (year.length() == 2) {
            year = "20" + year;
        }
        if (month.length() == 1) {
            month = '0' + month;
        }
        if (day.length() == 1) {
            day = '0' + day;
        }
        dateStr = year + "-" + month + "-" + day + "T" + other;
    } catch (final Exception e1) {
        throw GamaRuntimeException.error("The date " + original
                + " is not correctly formatted. Please refer to the ISO date/time format", scope);
    }

    try {
        result = LocalDateTime.parse(dateStr);
    } catch (final DateTimeParseException e) {
        try {
            result = OffsetDateTime.parse(dateStr);
        } catch (final DateTimeParseException e2) {
            try {
                result = ZonedDateTime.parse(dateStr);
            } catch (final DateTimeParseException e3) {
                throw GamaRuntimeException.error(
                        "The date " + original
                                + " is not correctly formatted. Please refer to the ISO date/time format",
                        scope);
            }
        }
    }

    return result;
}

From source file:be.wegenenverkeer.common.resteasy.json.Iso8601AndOthersLocalDateFormat.java

/**
 * Parse string to date./*from  w  w w. j  ava2  s  .  co m*/
 *
 * @param str string to parse
 * @return date
 */
public LocalDate parse(String str) {
    LocalDate date = null;

    if (!StringUtils.isBlank(str)) {
        // try ISO 8601 format first
        try {
            return LocalDate.from(iso8601NozoneFormat.parse(str));
        } catch (IllegalArgumentException | DateTimeParseException ex) {
            // ignore, try next format
            date = null; // dummy
        }

        // then try a list of formats
        for (DateTimeFormatter formatter : FORMATS) {
            try {
                return LocalDate.from(formatter.parse(str));
            } catch (IllegalArgumentException | DateTimeParseException e) {
                // ignore, try next format
                date = null; // dummy
            }
        }
        throw new IllegalArgumentException("Could not parse date " + str
                + " using ISO 8601 or any of the formats " + Arrays.asList(FORMATS) + ".");

    }
    return date; // empty string
}

From source file:be.wegenenverkeer.common.resteasy.json.Iso8601AndOthersLocalDateTimeFormat.java

/**
 * Parse string to date./* ww  w  .  java  2  s  . c  o  m*/
 *
 * @param str string to parse
 * @return date
 */
public LocalDateTime parse(String str) {
    LocalDateTime date = null;

    if (StringUtils.isNotBlank(str)) {
        // try full ISO 8601 format first
        try {
            Date timestamp = ISO8601Utils.parse(str, new ParsePosition(0));
            Instant instant = Instant.ofEpochMilli(timestamp.getTime());
            return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        } catch (IllegalArgumentException | ParseException ex) {
            // ignore, try next format
            date = null; // dummy
        }
        // then try ISO 8601 format without timezone
        try {
            return LocalDateTime.from(iso8601NozoneFormat.parse(str));
        } catch (IllegalArgumentException | DateTimeParseException ex) {
            // ignore, try next format
            date = null; // dummy
        }

        // then try a list of formats
        for (DateTimeFormatter formatter : FORMATS) {
            try {
                TemporalAccessor ta = formatter.parse(str);
                try {
                    return LocalDateTime.from(ta);
                } catch (DateTimeException dte) {
                    return LocalDate.from(ta).atStartOfDay();
                }
            } catch (IllegalArgumentException | DateTimeParseException e) {
                // ignore, try next format
                date = null; // dummy
            }
        }
        throw new IllegalArgumentException("Could not parse date " + str
                + " using ISO 8601 or any of the formats " + Arrays.asList(FORMATS) + ".");

    }
    return date; // empty string
}

From source file:com.att.aro.datacollector.ioscollector.utilities.AppSigningHelper.java

private boolean isProvProfileExpired() throws IOSAppException {
    DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
    Instant dateTime = Instant.from(formatter.parse(provProfile.getExpiration()));
    return dateTime.compareTo(Instant.now()) < 0;
}

From source file:org.apache.drill.exec.store.solr.SolrRecordReader.java

private void processRecord(ValueVector vv, Object fieldValue, int recordCounter) {
    String fieldValueStr = null;//w ww .jav a2s .  co m
    byte[] record = null;
    try {
        fieldValueStr = fieldValue.toString();
        record = fieldValueStr.getBytes(Charsets.UTF_8);

        if (vv.getClass().equals(NullableVarCharVector.class)) {
            NullableVarCharVector v = (NullableVarCharVector) vv;
            v.getMutator().setSafe(recordCounter, record, 0, record.length);
            v.getMutator().setValueLengthSafe(recordCounter, record.length);
        } else if (vv.getClass().equals(NullableBigIntVector.class)) {
            NullableBigIntVector v = (NullableBigIntVector) vv;
            BigDecimal bd = new BigDecimal(fieldValueStr);
            v.getMutator().setSafe(recordCounter, bd.longValue());
        } else if (vv.getClass().equals(NullableIntVector.class)) {
            NullableIntVector v = (NullableIntVector) vv;
            v.getMutator().setSafe(recordCounter, Integer.parseInt(fieldValueStr));
        } else if (vv.getClass().equals(NullableFloat8Vector.class)) {
            NullableFloat8Vector v = (NullableFloat8Vector) vv;
            Double d = Double.parseDouble(fieldValueStr);
            v.getMutator().setSafe(recordCounter, d);
        } else if (vv.getClass().equals(DateVector.class)) {
            DateVector v = (DateVector) vv;
            long dtime = 0L;
            try {
                TemporalAccessor accessor = SolrRecordReader.timeFormatter.parse(fieldValueStr);
                Date date = Date.from(Instant.from(accessor));
                dtime = date.getTime();
            } catch (Exception e) {
                SimpleDateFormat dateParser = new SimpleDateFormat(SolrRecordReader.defaultDateFormat);
                dtime = dateParser.parse(fieldValueStr).getTime();
            }

            v.getMutator().setSafe(recordCounter, dtime);
        } else if (vv.getClass().equals(NullableTimeStampVector.class)) {
            NullableTimeStampVector v = (NullableTimeStampVector) vv;
            DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
            long dtime = 0L;

            try {
                TemporalAccessor accessor = timeFormatter.parse(fieldValueStr);
                Date date = Date.from(Instant.from(accessor));
                dtime = date.getTime();
            } catch (Exception e) {
                SimpleDateFormat dateParser = new SimpleDateFormat(SolrRecordReader.defaultDateFormat);
                dtime = dateParser.parse(fieldValueStr).getTime();
            }
            v.getMutator().setSafe(recordCounter, dtime);
        }
    } catch (Exception e) {
        SolrRecordReader.logger.error("Error processing record: " + e.getMessage() + vv.getField().getPath()
                + " Field type " + vv.getField().getType() + " " + vv.getClass());
    }
}

From source file:org.talend.dataquality.statistics.datetime.DateTimePatternManager.java

private static boolean isDateTime(Map<DateTimeFormatter, String> parsers, String value) {
    if (StringUtils.isNotEmpty(value)) {
        // 1. The length of date characters should not exceed 64.
        if (value.length() > 64) {
            return false;
        }/* www .  j  a v  a  2  s  . c om*/
        // 2. Check it by list of patterns
        for (DateTimeFormatter formatter : parsers.keySet()) {
            try {
                if (formatter.parse(value) != null) {
                    return true;
                }
            } catch (DateTimeParseException e) {
                // continue
            }
        }
    }
    return false;
}