Day of the Year
Problem
Given a string date in the format YYYY-MM-DD, return the day number of the year that this date represents (a value between 1 and 366).
date = "2019-02-10"41def day_of_year(date):
year, month, day = map(int, date.split("-"))
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
days[1] = 29
total = day
for m in range(month - 1):
total += days[m]
return total
function dayOfYear(date) {
const [year, month, day] = date.split("-").map(Number);
const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)) {
days[1] = 29;
}
let total = day;
for (let m = 0; m < month - 1; m++) total += days[m];
return total;
}
class Solution {
public int dayOfYear(String date) {
int year = Integer.parseInt(date.substring(0, 4));
int month = Integer.parseInt(date.substring(5, 7));
int day = Integer.parseInt(date.substring(8, 10));
int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
days[1] = 29;
}
int total = day;
for (int m = 0; m < month - 1; m++) total += days[m];
return total;
}
}
int dayOfYear(string date) {
int year = stoi(date.substr(0, 4));
int month = stoi(date.substr(5, 2));
int day = stoi(date.substr(8, 2));
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
days[1] = 29;
}
int total = day;
for (int m = 0; m < month - 1; m++) total += days[m];
return total;
}
Explanation
To find which numbered day of the year a date is, we simply add up the lengths of all the full months that come before it, then add the day-of-month on top.
We keep a fixed list days of month lengths [31, 28, 31, ...]. Before counting, we check whether the year is a leap year (divisible by 400, or by 4 but not 100). If so, we bump February to 29 by setting days[1] = 29.
Then we start total = day and loop over the months before the target month (range(month - 1)), adding each month's length. Because the date is given as YYYY-MM-DD, we first split it into the year, month, and day integers.
Example: "2019-02-10". 2019 is not a leap year, so February stays 28. We start total = 10, then add January's 31 days, giving 10 + 31 = 41. So it is the 41st day of the year.
There are at most 12 months to add, so this runs in constant time.