If I already have a date's month, day, and year as integers, what's the best way to use them to create a LocalDate
object? I found this post String to LocalDate , but it starts with a String
representation of the date.
Create LocalDate Object from Integers
Use LocalDate#of(int, int, int)
method that takes year, month and dayOfMonth.
You can create LocalDate like this, using ints
LocalDate inputDate = LocalDate.of(year,month,dayOfMonth);
and to create LocalDate from String you can use
String date = "04/04/2004";
inputDate = LocalDate.parse(date,
DateTimeFormat.forPattern("dd/MM/yyyy"));
You can use other formats too but you have to change String in forPattern(...)
In addition to Rohit's answer you can use this code to get Localdate from String
String str = "2015-03-15";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(str, formatter);
System.out.println(dateTime);
The format shown here ( year-month-date ) complies with the ISO 8601 standard. The java.time classes use that standard by default when parsing/generating textual representations of date-time values. So no need to specify a formatting pattern; you can skip the
DateTimeFormatter
. Let LocalDate
directly parse that string, like this: … = LocalDate.parse( "2015-03-15" );
–
Heptachord © 2022 - 2025 — McMap. All rights reserved.
1
(this may seem obvious, but this is Java). – Riplex