-6

if I only have the year, the month, and the day, how do I initialize a LocalDateTime variable? also if I need to include time, I will just set it to 00:00:00 thank you so much!

Jenn
  • 1
  • 1
  • 1
  • https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#of-int-int-int-int-int-, https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#of-java.time.LocalDate-java.time.LocalTime-, https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#atStartOfDay-- – JB Nizet Jan 17 '20 at 20:22
  • 1
    Check out the documentation of [`LocalDateTime`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/time/LocalDateTime.html). It provides multiple static methods for creating instances, just use `0` for arguments pertaining to time. – Slaw Jan 17 '20 at 20:23
  • "Include tme"? What do you mean? Could you please provide some samle input and the expected outcome? It´s pretty unclear what you want to achieve. – MakePeaceGreatAgain Jan 17 '20 at 23:14

1 Answers1

2

The elegant way goes through a LocalDate:

    LocalDateTime dateTime = LocalDate.of(2020, Month.JANUARY, 18).atStartOfDay();
    System.out.println(dateTime);

Output from this snippet is:

2020-01-18T00:00

If you’ve got the month as a number, like 1 for January, use LocalDate.of(2020, 1, 18) instead. The rest is the same.

Think twice before using LocalDateTime. We usually use date and time together for establishing a point in time. LocalDateTime is unsuited for that (some will say that it can’t). Why and how? It doesn’t know any time zone or offset from UTC. So any person and any piece of software reading the LocalDateTime is free to interpret it into any time zone they happen to think of and not the intended one. For at least 19 out of 20 purposes you’re better off with either a ZonedDateTime or an OffsetDateTime. For example:

    ZoneId zone = ZoneId.of("America/Recife");
    ZonedDateTime dateTime = LocalDate.of(2020, Month.JANUARY, 18).atStartOfDay(zone);

2020-01-18T00:00-03:00[America/Recife]

The -03:00 between the minutes and the zone ID is the offset from UTC. Now we’re leaving no room for misinterpretation.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161