Find the week of the year with a date in mm / dd / yyyy

I am trying to find the week that the date is for a given year. I have a bunch of files that need to be sorted by folders like "week1-2012" and "week34-2011". I tried the search, but many of the results don't really help, because I'm currently using perl v5.6.1, super old, and I cannot load any modules. I also found this link ( How to calculate the week number with the date? ), But I wondered how I would strive to get the day of the year and the week, I thought about getting the month and added the appropriate number of days to find out the day of the year. Any help would be greatly appreciated. An example of the format of the year I'm looking for is

//year 2012
S  M  T  W  R  F  S
            1  2  3    <-- week #1 
4  5  6  7  8  9 10    <-- week #2 //came from the link

//dec year 2011
S   M  T  W  T  F  S
27 28 29 31            <-- week #52 or 53, not to sure the actual week
+5
source share
3 answers

You can use the base modules: POSIXandTime::Local

1. Mark the date (sec, min, hour, day, month, year)

2. convert your date in seconds (era)

3. Use the strftime function to get a week from the current date

use strict;
use Time::Local;
use POSIX qw(strftime);

my $date = '08/15/2012';
my ($month, $day, $year) = split '/', $date;

my $epoch = timelocal( 0, 0, 0, $day, $month - 1, $year - 1900 );
my $week  = strftime( "%U", localtime( $epoch ) );

printf "Date: %s № Week: %s\n", $date, $week;

OUTPUT

Date: 08/15/2012 № Week: 33
+7
source

Here's an alternative solution using DateTime:

use strict;
use warnings;
use DateTime;

my $dt=DateTime->now(time_zone=>"local");
print $dt->week_number . "\n";

The output, of course:

33

Edit: Of course you can download modules! If nothing else, you can copy and use the appropriate code from DateTime.

+3
source

Perl 5.6.1 2001 . - , , . .

Perl 5.10 , Time:: Piece. .

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Time::Piece;

my $date = '08/15/2012';

my $dt = Time::Piece->strptime($date, '%m/%d/%Y');

say $dt->strftime('week%W-%Y');

:

$ ./week 
week33-2012

Mon-Sun, Sun-Sat.

+3
source

All Articles