-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDayOfYear.java
More file actions
35 lines (26 loc) · 946 Bytes
/
Copy pathDayOfYear.java
File metadata and controls
35 lines (26 loc) · 946 Bytes
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
package LeetcodePractice;
public class DayOfYear {
public static int dayOfYear(String date) {
String[] parts = date.split("-");
int year = Integer.parseInt(parts[0]);
int month = Integer.parseInt(parts[1]);
int day = Integer.parseInt(parts[2]);
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) {
daysInMonth[1] = 29;
}
int dayOfYear = day;
for (int i = 0; i < month - 1; i++) {
dayOfYear += daysInMonth[i];
}
return dayOfYear;
}
private static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public static void main(String[] args) {
System.out.println(dayOfYear("2019-01-09"));
System.out.println(dayOfYear("2019-02-10"));
System.out.println(dayOfYear("2020-03-01"));
}
}