Tim 1:

获取本地时间:

calendar类获取本地时间的时间戳类型
可以通过get方式分别得到年月日时分秒
也可以通过 SimpleDateFormat类转成YYYY-MM-dd HH-mm-ss 年月日时分秒类型

int year, month, day, week, hh; 
         Calendar calendar = Calendar.getInstance(); 
         //调试输出calendar 
         System.err.println(calendar); 
         year = calendar.get(Calendar.YEAR); 
         month = calendar.get(Calendar.MONTH); 
        day = calendar.get(Calendar.DAY_OF_MONTH); 
         week = calendar.get(Calendar.DAY_OF_WEEK); 
         hh = calendar.get(Calendar.HOUR); 
         SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); 
         System.out.println("date=" + dateFormat.format(calendar.getTime())); 
         System.out.println("year=" + year); 
         System.out.println("month=" + month); 
         System.out.println("day=" + day); 
         System.out.println("week=" + week); 
         System.out.println("hh=" + hh);


Tim 2:


获取网络时间

取百度当前时间
定义网址:String Baiurl="http://www.baidu.com";
利用URl访问网址getdate获取时间得到当前网络时间 

再用SimpleDateFormat抓华日期时间型

ps:http一定要带上哦 不错会抱网络类型错误哦。





public static void main(String[] args) { 
         String Baiurl="http://www.baidu.com"; 
         System.err.println(getTime(Baiurl)); 
} 
public static String getTime(String Baiurl) { 
try { 
URL url = new URL(Baiurl);// 取得资源对象 
            URLConnection uc = url.openConnection();// 生成连接对象 
            uc.connect();// 发出连接 
            long ld = uc.getDate();// 读取网站日期时间 
            Date date = new Date(ld);// 转换为标准时间对象 
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 输出北京时间 
            return sdf.format(date); 
} catch (Exception e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 
return null; 
}