Reputation: 41
If I only have the year, month and day, how do I initialize a LocalDateTime instance?
If I have to include time, I will just set it to 00:00:00.
Upvotes: -2
Views: 12249
Reputation: 86120
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.
Upvotes: 7