perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 347 - Task 1: Format Date

  1 #!/usr/bin/env perl
  2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-347/#TASK1
  3 #
  4 # Task 1: Format Date
  5 # ===================
  6 #
  7 # You are given a date in the form: 10th Nov 2025.
  8 #
  9 # Write a script to format the given date in the form: 2025-11-10 using the set below.
 10 #
 11 # @DAYS   = ("1st", "2nd", "3rd", ....., "30th", "31st")
 12 # @MONTHS = ("Jan", "Feb", "Mar", ....., "Nov",  "Dec")
 13 # @YEARS  = (1900..2100)
 14 #
 15 #
 16 ## Example 1
 17 ##
 18 ## Input: $str = "1st Jan 2025"
 19 ## Output: "2025-01-01"
 20 #
 21 #
 22 ## Example 2
 23 ##
 24 ## Input: $str = "22nd Feb 2025"
 25 ## Output: "2025-02-22"
 26 #
 27 #
 28 ## Example 3
 29 ##
 30 ## Input: $str = "15th Apr 2025"
 31 ## Output: "2025-04-15"
 32 #
 33 #
 34 ## Example 4
 35 ##
 36 ## Input: $str = "23rd Oct 2025"
 37 ## Output: "2025-10-23"
 38 #
 39 #
 40 ## Example 5
 41 ##
 42 ## Input: $str = "31st Dec 2025"
 43 ## Output: "2025-12-31"
 44 #
 45 ############################################################
 46 ##
 47 ## discussion
 48 ##
 49 ############################################################
 50 #
 51 # Since we can pick the year as-is, we just need to translate
 52 # the day and month. So we get the index of the saved strings
 53 # for both in an array, add one to get the day/month as a number,
 54 # and add a leading 0 if necessary.
 55 
 56 use v5.36;
 57 
 58 my @DAYS   = get_days();
 59 my @MONTHS = get_months();
 60 my @YEARS  = (1900..2100);
 61 
 62 format_date("1st Jan 2025");
 63 format_date("22nd Feb 2025");
 64 format_date("15th Apr 2025");
 65 format_date("23rd Oct 2025");
 66 format_date("31st Dec 2025");
 67 
 68 sub format_date($str) {
 69     say "Input: '$str'";
 70     my ($d, $m, $y) = split /\s+/, $str;
 71     my $output = "${y}-" . indexed($m, @MONTHS) . "-" . indexed($d, @DAYS);
 72     say "Output: '$output'";
 73 }
 74 
 75 sub indexed($str, @array) {
 76     foreach my $i (0..$#array) {
 77         if($str eq $array[$i]) {
 78             return sprintf("%02d", $i+1);
 79         }
 80     }
 81     return sprintf("%02d", 0); # fallback
 82 }
 83 
 84 sub get_days() {
 85     my @DAYS   = ("1st", "2nd", "3rd");
 86     foreach(4..20) {
 87         push @DAYS, "${_}th";
 88     }
 89     push @DAYS, "21st";
 90     push @DAYS, "22nd";
 91     push @DAYS, "23rd";
 92     foreach(24..30) {
 93         push @DAYS, "${_}th";
 94     }
 95     push @DAYS, "31st";
 96     return @DAYS;
 97 }
 98 
 99 sub get_months() {
100     return ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",  "Dec");
101 }
102