Create LocalDate Object from Integers
Asked Answered
T

3

27

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.

Trabue answered 15/3, 2015 at 15:12 Comment(0)
A
42

Use LocalDate#of(int, int, int) method that takes year, month and dayOfMonth.

Asiaasian answered 15/3, 2015 at 15:13 Comment(1)
Months and days start at 1 (this may seem obvious, but this is Java).Riplex
H
20

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(...)

Hasten answered 26/4, 2016 at 10:42 Comment(0)
S
8

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);
Suppositious answered 15/3, 2015 at 15:19 Comment(1)
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.