10000 Convert between Date and YearMonth · andro-dev/Java-Coding-Problems@469355a · GitHub
[go: up one dir, main page]

Skip to content

Commit 469355a

Browse files
committed
Convert between Date and YearMonth
1 parent 21a1169 commit 469355a

File tree

4 files changed

+62
-0
lines changed

4 files changed

+62
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Converting `Iterable` to `List`
2+
Write a program that converts an `Iterable` to `List`.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>com.app</groupId>
5+
<artifactId>BONUS_1_ConvertYearMonthToDate</artifactId>
6+
<version>1.0-SNAPSHOT</version>
7+
<packaging>jar</packaging>
8+
<properties>
9+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
10+
<maven.compiler.source>13</maven.compiler.source>
11+
<maven.compiler.target>13</maven.compiler.target>
12+
</properties>
13+
<name>BONUS_1_ConvertYearMonthToDate</name>
14+
</project>
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package modern.challenge;
2+
3+
import java.time.YearMonth;
4+
import java.time.ZoneId;
5+
import java.util.Date;
6+
7+
public class Converters {
8+
9+
private Converters() {
10+
throw new AssertionError("Cannot be instantiatied");
11+
}
12+
13+
public static YearMonth toYearMonth(Date date) {
14+
15+
if (date == null) {
16+
throw new IllegalArgumentException("The given date cannot be null");
17+
}
18+
19+
return YearMonth.from(date.toInstant()
20+
.atZone(ZoneId.systemDefault())
21+
.toLocalDate());
22+
}
23+
24+
public static Date toDate(YearMonth ym) {
25+
26+
if (ym == null) {
27+
throw new IllegalArgumentException("The given year-month cannot be null");
28+
}
29+
30+
return Date.from(ym.atDay(1)
31+
.atStartOfDay(ZoneId.systemDefault()).toInstant());
32+
}
33+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package modern.challenge;
2+
3+
import java.time.YearMonth;
4+
import java.util.Date;
5+
6+
public class MainApplication {
7+
8+
public static void main(String[] args) {
9+
10+
System.out.println("Date to YearMonth: " + Converters.toYearMonth(new Date()));
11+
System.out.println("YearMonth to Date: " + Converters.toDate(YearMonth.now()));
12+
}
13+
}

0 commit comments

Comments
 (0)
0