javaintellij-idea2017

I can't use LocalDateTime


Both of them don't work. I wrote the errors after "—"

LocalDateTime date = new LocalDateTime.now(); // cannot resolve symbol 'now' 
LocalDateTime date = new LocalDateTime(); // LocalDateTime has private access

Solution

  • Your error message LocalDateTime has private access indicates that the compiler has imported LocalDateTime successfully.

    First, validate that you're using the LocalDateTime we expect. Look at the imports. You should see:

    import java.time.LocalDateTime;
    

    Now read the Javadoc for this class.

    new LocalDateTime() is trying to invoke a zero-argument constructor. The Javadoc does not list any constructors, because there are none that are not private.

    new LocalDateTime.now() is trying to invoke the zero-argument constructor of a class called LocalDateTime.now. There is no class with that name, which is why you get the error cannot resolve symbol 'now'

    What you actually want to do is to call the static method now() of the LocalDateTime class. To do that you do not use new.

    LocalDateTime now = LocalDateTime.now();
    

    Try creating your own class with static factory methods, and remind yourself how to call its methods.

    public class MyThing {
    
         private MyThing() { // private constructor
         };
    
         public static MyThing thing() {
             return new MyThing();
         }
    }
    

    You'll find that you get the same errors if you try to use this from another class with new MyThing() or new MyThing.thing(). MyThing.thing() will work.