-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathDateAndTime.java
75 lines (60 loc) · 2.15 KB
/
DateAndTime.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package potplayer;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
public class DateAndTime {
public static String readDateAndTime() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date dateTime = new Date(System.currentTimeMillis());
return formatter.format(dateTime);
}
public static String readDate() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.now();
return formatter.format(date);
}
public static String readTime() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime time = LocalTime.now();
return formatter.format(time);
}
public static String readWebDateAndTime(String webUrl, String format) {
if (webUrl == null) {
webUrl = "http://www.baidu.com";
}
try {
String wUrl = webUrl;
URL url = new URL(wUrl);
URLConnection urlConnect = url.openConnection();
urlConnect.setConnectTimeout(3000);
urlConnect.setReadTimeout(3000);
urlConnect.connect();
long unformatDate = urlConnect.getDate();
Date date = new Date(unformatDate);
String type = null;
if (format.equals("all")) {
type = "yyyy-MM-dd HH:mm:ss";
} else if (format.equals("time")) {
type = "HH:mm:ss";
} else if (format.equals("date")) {
type = "yyyy-MM-dd";
} else {
type = format;
}
SimpleDateFormat sdf = new SimpleDateFormat(type, Locale.CHINA);
return sdf.format(date);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}