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