java获取本地时间与网络时间


通过java.util.Date类获取本地时间:

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        System.out.println("date=" + dateFormat.format(date.getTime()));

通过网站获取网络时间:

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

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

      String webUrlt = "http://www.taobao.com";
      String webUrlb = "http://www.baidu.com";
      System.out.println(getNetworkTime(webUrlt) + " [淘宝]");
      System.out.println(getNetworkTime(webUrlb) + " [百度]");

    }
      public static String getNetworkTime(String webUrl) {
          try {
              URL url = new URL(webUrl);
              URLConnection conn = url.openConnection();
              conn.connect();
              long dateL = conn.getDate();
              Date date = new Date(dateL);
              SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
              return dateFormat.format(date);
          } catch (MalformedURLException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }

          return "";
      }

  }

最终结果:

2019-06-17 01:31:02 [淘宝]
2019-06-17 01:31:02 [百度]

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM