I am trying to use the LocalDate Java class and passing it as a parameter in the method. When I am instantiating the method in main method I need to pass the LocalDate as an argument, when I try '2019-08-16' it says too many literals, when I try "2019-08-16" it says cannot be applied to String.

import java.time.LocalDate;import java.time.format.DateTimeFormatter;public class LocalDateExample {public void localDate(LocalDate date) {String dayOfMonth = Integer.toString(date.getDayOfMonth());System.out.println("Day Of Month is" + dayOfMonth); // this throws error}public static void main(String[] args) {LocalDateExample dd = new LocalDateExample();dd.localDate("2019-08-16"); // this line throws error}}
2

Best Answer


TL;DR

 dd.localDate(LocalDate.of(2019, Month.AUGUST, 16));

Why so?

Since your method is declared to accept a LocalDate argument, you need to pass an instance of LocalDate (not a string or any other type). Java doesn’t have automatic type conversions, which is why it didn’t work with a string.

LocalDate and the other types of java.time have factory methods for creating objects. The most commonly used factory methods are simply named of. LocalDate has got two overloaded of methods. For most purposes I prefer to use the one accepting a Month enum constant as the middle argument as shown in the above example. The other one accepts an int for the month number (from 1 = January), so the following works too:

 dd.localDate(LocalDate.of(2019, 8, 16));

By the way with '2019-08-16' you had got a different problem since single quotes ' are used for character literals. '2' is a character literal, but it needs to denote one character, so you are not allowed to have more characters between the single quotes.

Finally despite the comment in your code the following line does not cause any error (so I have corrected the comment here):

 System.out.println("Day Of Month is" + dayOfMonth); // this works fine

Although I would recommend to consider renaming the function localDate(), especially when it asks for a LocalDate parameter:

public class LocalDateExample {public void localDate(LocalDate date) {String dayOfMonth = Integer.toString(date.getDayOfMonth());System.out.println("Day Of Month is " + dayOfMonth);}public static void main(String[] args) {LocalDateExample dd = new LocalDateExample();dd.localDate(LocalDate.parse("2019-08-16"));}}

Should work, as the comments suggest.