我不能使用 LocalDateTime

I can't use LocalDateTime

两者都不行。我把错误写在了“—”之后

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

你的语法不对,假设你使用的是 Java 8+,没有 import 它可能看起来像,

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

如果你有import java.time.LocalDateTime;那么你只需要

LocalDateTime date = LocalDateTime.now();

调用static LocalDateTime#now()(注意提供了多个now()函数,这使得有效使用不同时区变得更加容易)。

now() 是一个静态方法。试试这个:

LocalDateTime date = LocalDateTime.now();

你的错误信息LocalDateTime has private access表明编译器已经导入LocalDateTime成功。

首先,确认您使用的是我们期望的 LocalDateTime。看进口货。你应该看到:

import java.time.LocalDateTime;

现在阅读Javadoc for this class

new LocalDateTime() 正在尝试调用零参数构造函数。 Javadoc 没有列出任何构造函数,因为有 none 不是私有的。

new LocalDateTime.now() 正在尝试调用名为 LocalDateTime.now 的 class 的零参数构造函数。不存在具有该名称的 class,这就是您收到错误 cannot resolve symbol 'now'

的原因

您实际上想要做的是调用 LocalDateTime class 的静态方法 now()。为此,您不要使用new

LocalDateTime now = LocalDateTime.now();

尝试使用静态工厂方法创建您自己的 class,并提醒自己如何调用其方法。

public class MyThing {

     private MyThing() { // private constructor
     };

     public static MyThing thing() {
         return new MyThing();
     }
}

如果您尝试将另一个 class 与 new MyThing()new MyThing.thing() 一起使用,您会发现同样的错误。 MyThing.thing() 会起作用。