黑马程序员技术交流社区

标题: Date类中getTime方法的疑问 [打印本页]

作者: 吴硕    时间: 2013-2-28 18:15
标题: Date类中getTime方法的疑问
本帖最后由 吴硕 于 2013-3-1 11:10 编辑

getTime方法为什么每次返回的值都一样?
  1. import java.util.Date;
  2. /**

  3. */

  4. class DateTest
  5. {
  6.     public static void main(String[] args) throws Exception
  7.     {
  8.         Date d = new Date();
  9.         while(true)
  10.         {
  11.             long time = d.getTime();
  12.             System.out.println(time);
  13.             Thread.sleep(2000);
  14.         }
  15.     }
  16. }
复制代码




作者: 顾传文    时间: 2013-2-28 18:37
Date对象表示的是当前这个时刻的时间,并且精确到毫秒。
你在while里面循环,但是Date是同一个对象,并没有改变。你将创建对象语句放到while循环中,效果就不一样了。
import java.util.Date;

class Test
{
    public static void main(String[] args) throws Exception
    {
        Date d = null;
        while(true)
        {
                d = new Date();//没循环一次,重新创建Date实例
            long time = d.getTime();
            System.out.println(time);
            Thread.sleep(2000);
        }
    }
}
作者: 颜春    时间: 2013-2-28 22:17
Date.getTime();
返回:
自 1970 年 1 月 1 日 00:00:00 GMT 以来此日期表示的毫秒数。

想要得到当前时间
class DateTest
        {
            public static void main(String[] args) throws Exception
            {
                while(true)
                {
                    long time = System.currentTimeMillis();//获得系统当前时间
                    System.out.println(time);
                    Thread.sleep(2000);
                   
                }
                
            }
      
}


作者: 偏執旳、靑春    时间: 2013-3-1 10:35
getTime()这个对象创建的时间数,说白就是这个对象是什么时候创建的,不是用来取当前时间的方法,,你用错了方法。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2