美文网首页
java获取网络时间

java获取网络时间

作者: MacLi | 来源:发表于2020-04-24 10:58 被阅读0次
    public static long getNetTime() {
            Long currentTime = System.currentTimeMillis();
            URL url = null;//取得资源对象
            try {
                url = new URL("[http://www.b<wbr>aidu.com](http://www.baidu.com/)");
                //url = new URL("[http://www.n<wbr>tsc.ac.cn](http://www.ntsc.ac.cn/)");//中国科学院国家授时中心
                //url = new URL("[http://www.b<wbr>jtime.cn](http://www.bjtime.cn/)");
                URLConnection uc = url.openConnection();//生成连接对象
                uc.connect(); //发出连接
                long ld = uc.getDate(); //取得网站日期时间
                currentTime = ld;
                java.text.DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(ld);
                final String format = formatter.format(calendar.getTime());
                Log.d(TAG, "Net time:" + format);
    //       runOnUiThread(new Runnable() {
    //          @Override
    //          public void run() {
    //             Toast.makeText(MainActivity.this, "当前网络时间为: \n" + format, Toast.LENGTH_SHORT).show();
    //             tvNetTime.setText("当前网络时间为: \n" + format);
    //          }
    //       });
            } catch (Exception e) {
                e.printStackTrace();
            }
            return currentTime;
        }
    
    

    相关文章

      网友评论

          本文标题:java获取网络时间

          本文链接:https://www.haomeiwen.com/subject/dlvxwhtx.html