Test.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package testExport;
  2. import java.io.IOException;
  3. import java.net.MalformedURLException;
  4. import java.net.URL;
  5. import java.net.URLConnection;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Calendar;
  8. import java.util.Date;
  9. import java.util.Locale;
  10. public class Test {
  11. //记住不要导错包 代码亲测可用
  12. public static void main(String[] args) {
  13. String webUrl2 = "http://www.baidu.com";//百度
  14. String webUrl3 = "http://www.taobao.com";//淘宝
  15. String webUrl4 = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
  16. String webUrl5 = "http://www.360.cn";//360
  17. System.out.println(getWebsiteDatetime(webUrl2) + " [百度]");
  18. System.out.println(getWebsiteDatetime(webUrl3) + " [淘宝]");
  19. System.out.println(getWebsiteDatetime(webUrl4) + " [中国科学院国家授时中心]");
  20. System.out.println(getWebsiteDatetime(webUrl5) + " [360安全卫士]");
  21. Calendar cal = Calendar.getInstance();
  22. // 往前多少天的访客
  23. cal.add(Calendar.DATE, -1);
  24. String startTime = new SimpleDateFormat( "yyyyMMdd").format(cal.getTime());
  25. System.out.println(startTime);
  26. }
  27. /**
  28. * 获取指定网站的日期时间
  29. *
  30. * @param webUrl
  31. * @return
  32. */
  33. public static String getWebsiteDatetime(String webUrl){
  34. try {
  35. URL url = new URL(webUrl);// 取得资源对象
  36. URLConnection uc = url.openConnection();// 生成连接对象
  37. uc.connect();// 发出连接
  38. long ld = uc.getDate();// 读取网站日期时间
  39. Date date = new Date(ld);// 转换为标准时间对象
  40. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 输出北京时间
  41. return sdf.format(date);
  42. } catch (MalformedURLException e) {
  43. e.printStackTrace();
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }
  47. return null;
  48. }
  49. }