OnlineTime.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.happy.Until.Time;
  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 OnlineTime {
  11. public static String webUrl4 = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
  12. public static String getWebsiteDatetime(String webUrl){
  13. try {
  14. URL url = new URL(webUrl);// 取得资源对象
  15. URLConnection uc = url.openConnection();// 生成连接对象
  16. uc.connect();// 发出连接
  17. long ld = uc.getDate();// 读取网站日期时间
  18. Date date = new Date(ld);// 转换为标准时间对象
  19. System.out.println(date);
  20. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 输出北京时间
  21. return sdf.format(date);
  22. } catch (MalformedURLException e) {
  23. e.printStackTrace();
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. return null;
  28. }
  29. public static String getWebsiteDateday(String webUrl){
  30. try {
  31. URL url = new URL(webUrl);// 取得资源对象
  32. URLConnection uc = url.openConnection();// 生成连接对象
  33. uc.connect();// 发出连接
  34. long ld = uc.getDate();// 读取网站日期时间
  35. Date date = new Date(ld);// 转换为标准时间对象
  36. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 输出北京时间
  37. return sdf.format(date);
  38. } catch (MalformedURLException e) {
  39. e.printStackTrace();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. return null;
  44. }
  45. public static String time(){
  46. return getWebsiteDatetime(webUrl4);
  47. }
  48. public static String day(){
  49. return getWebsiteDateday(webUrl4);
  50. }
  51. public static void main(String[] args) {
  52. System.out.println(day());
  53. System.out.println(time());
  54. }
  55. }