perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 326 - Task 1: Day of the Year

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-326/#TASK1
 3 #
 4 # Task 1: Day of the Year
 5 # =======================
 6 #
 7 # You are given a date in the format YYYY-MM-DD.
 8 #
 9 # Write a script to find day number of the year that the given date represent.
10 #
11 ## Example 1
12 ##
13 ## Input: $date = '2025-02-02'
14 ## Output: 33
15 ##
16 ## The 2nd Feb, 2025 is the 33rd day of the year.
17 #
18 #
19 ## Example 2
20 ##
21 ## Input: $date = '2025-04-10'
22 ## Output: 100
23 #
24 #
25 ## Example 3
26 ##
27 ## Input: $date = '2025-09-07'
28 ## Output: 250
29 #
30 ############################################################
31 ##
32 ## discussion
33 ##
34 ############################################################
35 #
36 # We need to add up all days in the months up to before the current one.
37 # Then we need to add the day in the current month to that sum.
38 # We just need one little trick: An array with the number of days for
39 # each number so we can add those up easily. This in turn needs to check
40 # whether we're in a leap year so we can set February to 29 days instead
41 # of the usual 28.
42 
43 use v5.36;
44 
45 day_of_year('2025-02-02');
46 day_of_year('2025-04-10');
47 day_of_year('2025-09-07');
48 
49 sub day_of_year($date) {
50     say "Input: $date";
51     my ($y, $m, $d) = split /-/, $date;
52     $m =~ s/^0//;
53     $d =~ s/^0//;
54     my @mdays = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
55     $mdays[1] = 29 if is_leap_year($y);
56     my $s = 0;
57     foreach my $i (0..$m-2) {
58         $s += $mdays[$i];
59     }
60     $s += $d;
61     say "Output: $s";
62 }
63 
64 sub is_leap_year($year) {
65     if($year % 4) {
66         return 0;
67     }
68     if($year % 100 == 0) {
69         if($year % 400 == 0) {
70             return 1;
71         }
72         return 0;
73     }
74     return 1;
75 }