试图修复java中的解除引用错误

时间:2014-04-15 17:50:33

标签: java

我有一个问题,我正试图从“宇宙的新起点”(即1970年1月1日)中找到特定长值的日期和时间。

当我尝试将新值传递给toString时,我收到“无法解除引用”错误。

我不知道的是,这适用于以毫秒获得时间并显示更易读的日期/时间格式,那么为什么不在我用它做一堆数学之后呢?

    import java.util.*;

public class Date {
public static void main(String[] args) {


    Date mydate1 = new Date(10000);
    System.out.println("The date and time of " +
        mydate1.elapse + " from the Unix epoch is " + mydate1.getMyTime());

    Date mydate2 = new Date(100000);
    System.out.println("The date and time of " +
        mydate2.elapse + " from the Unix epoch is " + mydate2.getMyTime());

    Date mydate3 = new Date(1000000);
    System.out.println("The date and time of " +
        mydate3.elapse + " from the Unix epoch is " + mydate3.getMyTime());

    Date mydate4 = new Date(10000000);
    System.out.println("The date and time of " +
        mydate4.elapse + " from the Unix epoch is " + mydate4.getMyTime());

    Date mydate5 = new Date(100000000);
    System.out.println("The date and time of " +
        mydate5.elapse + " from the Unix epoch is " + mydate5.getMyTime());

    Date mydate6 = new Date(1000000000);
    System.out.println("The date and time of " +
        mydate6.elapse + " from the Unix epoch is " + mydate6.getMyTime());

    /*Date date7 = new Date(10000000000);
    System.out.println("The date and time of " +
        date7.elapse + " from the Unix epoch is " + date7.getTime());

    Date date8 = new Date(100000000000);
    System.out.println("The date and time of " +
        date8.elapse + " from the Unix epoch is " + date8.getTime());*/
}

long elapse;

Date() {
    elapse = 1;
}

Date(long elapseTime) {
    elapse = elapseTime;
}



long getMyTime() {
    //java.util.Date date = new.java.util.Date();
    long currentMillis = System.currentTimeMillis();

    long date = currentMillis + elapse - currentMillis;
    System.out.println(date.toString());

3 个答案:

答案 0 :(得分:0)

您无法在toString()(原始类型) -

上调用long
// System.out.println(date.toString());
System.out.println(date);                 // <-- this would work.
System.out.println(String.valueOf(date)); // <-- this would be assignable to a
                                          //     String, but it prints the 
                                          //     same value as the first example.

答案 1 :(得分:0)

问题在于:System.out.println(date.toString())

date是基本类型long(它不是包装类Long的对象)。因此,toString()方法不适用于&#39; date&#39;。而你可以简单地使用:

System.out.println(date);

如果要打印格式化的日期,请使用以下内容:

Dste d = new Date(date);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
System.out.println(sdf.format(d));

答案 2 :(得分:0)

long date = currentMillis + elapse - currentMillis;

变量date是基元(long),而不是对象。 toString是所有java类从java.lang.Object继承的方法,因此可用于所有对象(即类的实例)。 long只是一个原始的,原语没有方法,它们也不会从Object继承。

所以你需要的只是

  System.out.println(date);