forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateTimes.java
More file actions
48 lines (33 loc) · 1.25 KB
/
Copy pathDateTimes.java
File metadata and controls
48 lines (33 loc) · 1.25 KB
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
package modern.challenge;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public final class DateTimes {
private DateTimes() {
throw new AssertionError("Cannot be instantiated");
}
public static String fromDateAsString(Date date, String pattern) {
if (date == null || pattern == null || pattern.isBlank()) {
// or throw IllegalArgumentException
return "";
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}
public static Date fromDateAsDate(Date date) throws ParseException {
if (date == null) {
throw new IllegalArgumentException("Date cannot be null");
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dateWithoutTime = sdf.parse(sdf.format(date));
return dateWithoutTime;
}
public static Date fromDateAsTime(Date date) throws ParseException {
if (date == null) {
throw new IllegalArgumentException("Date cannot be null");
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date timeWithoutDate = sdf.parse(sdf.format(date));
return timeWithoutDate;
}
}