-2

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
Jules Dupont
  • 7,259
  • 7
  • 39
  • 39
Kadzii
  • 13
  • 1
  • 2

4 Answers4

1

now() is a static method. Try this:

LocalDateTime date = LocalDateTime.now();
jiyarza
  • 11
  • 2
1

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.

slim
  • 40,215
  • 13
  • 94
  • 127
0

Your syntax is off, assuming you're using Java 8+, without an import it might look like,

java.time.LocalDateTime date = java.time.LocalDateTime.now(); 

and if you have import java.time.LocalDateTime; then you only need

LocalDateTime date = LocalDateTime.now();

to invoke the static LocalDateTime#now() (note there are multiple now() functions provided, this makes it much easier to effectively use different time zones).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • I already imported, but LocalDateTime date = LocalDateTime.now() doesn't work. "Java:cannot find symbol" – Kadzii Feb 05 '18 at 15:26
  • 1
    @Kadzii Then you must be setup to target a version of Java earlier than 8. Because `LocalDateTime` wasn't added until version 8 of Java. – Elliott Frisch Feb 05 '18 at 15:32
  • How can I do that? – Kadzii Feb 05 '18 at 16:02
  • You probably do have Java 8 already. The compiler error `LocalDateTime has private access` indicates that the class exists and that you've imported it. – slim Feb 05 '18 at 16:43
0

I know it's too late but in case if anyone have a same issue.

If you get error just for now() section probably the issue is from your minimum SDK.

For using LocalDateTime.now() you must set the minSdk to 26.

Hope it helps.

Sam Sh
  • 1