URL url = new URL("http://time.tianqi.com/");//取得资源对象
URLConnection urlConnection = url.openConnection();//生成连接对象
urlConnection.connect(); //发出连接
long ld = urlConnection.getDate(); //取得网站日期时间
Date date = new Date(ld); //转换为标准时间对象
//分别取得时间
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
System.out.println("年:" + year);
int month = cal.get(Calendar.MONTH) + 1;
String month1 = isDecimalFormat(month);
System.out.println("月:" +month1 );
int DATE = cal.get(Calendar.DATE);
String date1 = isDecimalFormat(DATE);
System.out.println("日:" + date1);
int Hours = cal.get(Calendar.HOUR_OF_DAY);
String Hours1 = isDecimalFormat(Hours);
System.out.println("时:" + Hours1);
int MINUTE = cal.get(Calendar.MINUTE);
String MINUTE1 = isDecimalFormat(MINUTE);
System.out.println("分:" + MINUTE1);
int SECOND = cal.get(Calendar.SECOND);
String SECOND1 = isDecimalFormat(SECOND);
System.out.println("秒:" + SECOND1);
//注意!拼接格式一定要按照yyyy-MM-dd HH:mm:ss,或者把Uuid类中的转换格式的方法改掉就可以了
String Time =year +"-"+ month1 +"-"+ date1 +" "+ Hours1 +":"+ MINUTE1 +":"+ SECOND1;
System.out.println("String类型的北京时间为:"+Time);
//String转为Date
Date dateTime = Time(Time);
System.out.println("Date格式的日期为:"+dateTime);
}
public static String isDecimalFormat(int a){
int str1=a;
DecimalFormat df=new DecimalFormat("00");
String str2=df.format(str1);
return str2;
}
//String类型转换为Date
public static Date Time(String a) throws ParseException {
//获得时间格式字符串
String ds = a;
//获得SimpleDateFormat类,我们转换为yyyy-MM-dd HH:mm:ss的时间格式
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sf.parse(ds);
return date;
}
运行结果如下:
以上结果可以看到我本地电脑设置的是2023-05-30 17:29,实际真实的时间是2023-05-31 17:28:12
注意事项:该方法一定要联网,否则会报错