0

I am getting date-time strings in the format "2021-04-25 04:27:35" (YYYY-MM-DD hh:mm:ss) and need to convert them to "2021w18". I must get the weeknumber and I already have the below in my perl script.

use Time::Piece;
use POSIX qw(strftime);

Any help will help me progress beyond "newbie".

  • 1
    Where on earth (or elsewhere) is the week of 2021-04-25 the 18th? – Armali May 25 '21 at 14:27
  • _..I already have the below in my perl script_. Your code is not evaluating anything apart from loading the above two Perl libraries/modules. First you must understand what does [use](https://perldoc.perl.org/functions/use) does. – vkk05 May 25 '21 at 15:06
  • 2
    Hope [this](https://stackoverflow.com/questions/11974992/find-week-of-a-year-given-the-date-in-mm-dd-yyyy) could help you to get the right result. – vkk05 May 25 '21 at 15:13

1 Answers1

3

Here's a subroutine that will do what you want:

use Time::Piece;
use POSIX qw(strftime);
use strict;
use warnings;
use feature 'say';
sub dateToWeek {
    my ($date) = @_;
    my $t = Time::Piece->strptime($date, "%Y-%m-%d %H:%M:%S");
    return $t->strftime("%Yw%U");
}
say dateToWeek("2021-04-25 04:27:35");

Output:

2021w17

Pass it a date contained in a string and it will return the year + "w" + week number. If you need it to return 2021w18 instead of 2021w17 for April 25, 2021, change the return statement to add 1 to the strftime like so:

return $t->year . "w" . ($t->strftime("%U")+1);
Nathan Mills
  • 2,243
  • 2
  • 9
  • 15
  • 1
    Rather than `$t->year . "w" . $t->strftime("%U")` (which looks rather complicated), you could just use `$t->strftime("%Yw%U")`. – Dave Cross May 26 '21 at 10:47