Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 48e3602

Browse files
feat(problem #81): add day-of-the-year
1 parent d0b479d commit 48e3602

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎Easy/day-of-the-year.cs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
public class Solution
2+
{
3+
#region Without Using Built-In Functions
4+
public static bool IsLeapYear(short year)
5+
=> (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
6+
7+
public static byte DaysInMonth(short year, byte month)
8+
{
9+
if (month < 1 || month > 12)
10+
{
11+
return 0;
12+
}
13+
14+
byte[] daysInMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
15+
16+
return (month == 2) ? (byte)(IsLeapYear(year) ? 29 : 28) : (daysInMonth[month]);
17+
}
18+
19+
public static int DayOfYear(string date)
20+
{
21+
if (!DateTime.TryParse(date, out DateTime dateObject))
22+
{
23+
return -1;
24+
}
25+
26+
int totalDays = 0;
27+
28+
for (byte i = 1; i < dateObject.Month; i++)
29+
{
30+
totalDays += DaysInMonth((short)dateObject.Year, i);
31+
}
32+
33+
return (totalDays + dateObject.Day);
34+
}
35+
#endregion
36+
37+
#region Using Built-In Functions
38+
public static int DayOfYear2(string date)
39+
{
40+
if (!DateTime.TryParse(date, out DateTime dateObject))
41+
{
42+
return -1;
43+
}
44+
45+
return dateObject.DayOfYear;
46+
}
47+
#endregion
48+
49+
private static void Main()
50+
{
51+
Console.WriteLine(DayOfYear("2019年02月10日"));
52+
Console.ReadKey();
53+
}
54+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /