我不能使用LocalDateTime

时间:2018-02-05 15:18:09

标签: java intellij-idea2017

它们都不起作用。我在“ - ”之后写了错误

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

3 个答案:

答案 0 :(得分:1)

您的错误消息LocalDateTime has private access表示编译器已成功导入LocalDateTime

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

import java.time.LocalDateTime;

现在阅读Javadoc for this class

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

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

的原因

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

LocalDateTime now = LocalDateTime.now();

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

public class MyThing {

     private MyThing() { // private constructor
     };

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

如果您尝试在另一个使用new MyThing()new MyThing.thing()的班级中使用此错误,您会发现同样的错误。 MyThing.thing()可以使用。

答案 1 :(得分:0)

您的语法已关闭,假设您使用的是Java 8+,而它可能看起来不像import

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

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

LocalDateTime date = LocalDateTime.now();

调用static LocalDateTime#now()(请注意,提供了多个now()函数,这样可以更轻松地有效地使用不同的时区。)

答案 2 :(得分:0)

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

LocalDateTime date = LocalDateTime.now();