A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 吴硕 中级黑马   /  2013-2-28 18:15  /  2527 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 吴硕 于 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. }
复制代码



评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1

查看全部评分

3 个回复

倒序浏览
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);
        }
    }
}

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1

查看全部评分

回复 使用道具 举报
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);
                   
                }
                
            }
      
}

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1

查看全部评分

回复 使用道具 举报
getTime()这个对象创建的时间数,说白就是这个对象是什么时候创建的,不是用来取当前时间的方法,,你用错了方法。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马