Can't Parse String to Localdate (Java 8)

Can't parse String to LocalDate (Java 8)

For year you have to use the lowercase y:

final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd-MM-yyyy");

Uppercase Y is used for weekyear. See the javadoc of DateTimeFormatter for more details.

Java 8 LocalDate won't parse valid date string

An example from the documentation:

LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);

You should use "yyyyMMdd" instead of "YYYYMMdd". The difference between Y and y was mentioned here.

Convert String to LocalDateTime Java 8

You don't need to specify a DateTimeFormatter in this case because the default one will be used if you don't pass one at all:

public static void main(String[] args) {
String dateStr = "2020-08-17T10:11:16.908732";
// the following uses the DateTimeFormatter.ISO_LOCAL_DATE_TIME implicitly
LocalDateTime dateTime = LocalDateTime.parse(dateStr);
System.out.println(dateTime);
}

That code will output 2020-08-17T10:11:16.908732.

If you are insisting on using a custom DateTimeFormatter, consider the T by single-quoting it in the pattern and don't use nanosecond parsing (n) for parsing fractions of second (S), the result might be wrong otherwise.

Do it like this:

public static void main(String[] args) {
String dateStr = "2020-08-17T10:11:16.908732";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
LocalDateTime dateTime = LocalDateTime.parse(dateStr, format);
System.out.println(dateTime);
}

with the same output as above.

Note:

The result of using the pattern "yyyy-MM-dd'T'HH:mm:ss.nnnnnn" would not be equal to the parsed String, instead, it would be

2020-08-17T10:11:16.000908732

How to parse string (such as Sunday, July 4, 2021) to LocalDate?

Try it like this.

String s = "Sunday, July 4, 2021";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEEE, LLLL d, yyyy");
LocalDate ld = LocalDate.parse(s, dtf);
System.out.println(ld);

prints

2021-07-04

Read up on DateTimeFormatter if you want to change the output format.

Note: If the day of the week is wrong for the numeric day of the month, you will get a parsing error. To avoid this, just skip over or otherwise ignore the day of the week.

Parsing a year String to a LocalDate with Java8

LocalDate parsing requires that all of the year, month and day are specfied.

You can specify default values for the month and day by using a DateTimeFormatterBuilder and using the parseDefaulting methods:

DateTimeFormatter format = new DateTimeFormatterBuilder()
.appendPattern("yyyy")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter();

LocalDate.parse("2008", format);

How can I parse/format dates with LocalDateTime? (Java 8)

Parsing date and time

To create a LocalDateTime object from a string you can use the static LocalDateTime.parse() method. It takes a string and a DateTimeFormatter as parameter. The DateTimeFormatter is used to specify the date/time pattern.

String str = "1986-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

Formatting date and time

To create a formatted string out a LocalDateTime object you can use the format() method.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.of(1986, Month.APRIL, 8, 12, 30);
String formattedDateTime = dateTime.format(formatter); // "1986-04-08 12:30"

Note that there are some commonly used date/time formats predefined as constants in DateTimeFormatter. For example: Using DateTimeFormatter.ISO_DATE_TIME to format the LocalDateTime instance from above would result in the string "1986-04-08T12:30:00".

The parse() and format() methods are available for all date/time related objects (e.g. LocalDate or ZonedDateTime)

Unable to Convert Formatted String to LocalDateTime

You should not have single quotes in your input String, and your pattern is off. You wanted yyyy (not YYYY). Like,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"EEE MMMM d yyyy hh:mm:ss a", Locale.US);
String timestamp = "Fri August 16 2019 12:08:55 AM";
LocalDateTime localDateTime = LocalDateTime.parse(timestamp, formatter);
System.out.println(localDateTime);

Outputs (here)

2019-08-16T00:08:55

Parsing string to local date doesn't use desired century

Since this question is really about new java.time-package and NOT SimpleDateFormat I will cite following relevant section:

Year: The count of letters determines the minimum field width below
which padding is used. If the count of letters is two, then a reduced
two digit form is used. For printing, this outputs the rightmost two
digits. For parsing, this will parse using the base value of 2000,
resulting in a year within the range 2000 to 2099 inclusive.

We see that Java-8 uses the range 2000-2099 per default, not like SimpleDateFormat the range -80 years until +20 years relative to today.

If you want to configure it then you have to use appendValueReduced(). This is designed in an inconvenient way, but possible, see here:

String s = "150790";

// old code with base range 2000-2099
DateTimeFormatter dtf1 =
new DateTimeFormatterBuilder().appendPattern("ddMMyy").toFormatter();
System.out.println(dtf1.parse(s)); // 2090-07-15

// improved code with base range 1935-2034
DateTimeFormatter dtf2 =
new DateTimeFormatterBuilder().appendPattern("ddMM")
.appendValueReduced(
ChronoField.YEAR, 2, 2, Year.now().getValue() - 80
).toFormatter();
System.out.println(dtf2.parse(s)); // 1990-07-15

By the way, if you really want week-based years then you have to use Y instead of y or the appropriate field IsoFields.WEEK_BASED_YEAR. Regarding the fact that you don't have any other week-related fields I would assume the normal calendar year, not the week-based one.



Related Topics



Leave a reply



Submit