in reply to How to find first day of the first week on the month?

G'day devbond,

"i need to find the first day of the first week of a month."

Firstly, that seems an odd way to ask this. I'm assuming, for a given year and month, you want to know what day (e.g. Sunday) the 1st of that month is. If that's not what you meant, please clarify.

There's a plethora of modules on CPAN that can do this type of thing; however, the builtin module, Time::Piece, can also do this and you already have it installed. So, unless you're already using some Date::*, Time::*, etc. module, Time::Piece is probably your best choice. Here's sample code:

#!/usr/bin/env perl -l use strict; use warnings; use Time::Piece; # In 2 days it will be Tuesday, 1st October 2013 my $month = 10; my $year = 2013; my $day_name = Time::Piece->strptime("$year$month" . '01', '%Y%m%d')-> +fullday; print "01-Oct-2013 is a $day_name";

Output:

01-Oct-2013 is a Tuesday

-- Ken

Replies are listed 'Best First'.
Re^2: How to find first day of the first week on the month?
by BillKSmith (Monsignor) on Sep 29, 2013 at 00:10 UTC

    It sure is an odd question. I thought he meant "What is the date of the first Sunday (or perhaps Monday) of the month?"

    Bill

      You could be right. We'll have to wait for devbond to tell us. Anyway, that's just as easy to calculate:

      #!/usr/bin/env perl -l use strict; use warnings; use Time::Piece; my $month = 10; my $year = 2013; for (1 .. 7) { # Time::Piece->wday returns: Sunday = 1, ..., Saturday += 7 print +($_ - Time::Piece->strptime("$year$month" . '01', '%Y%m%d') +->wday) % 7 + 1; }

      Output:

      6 7 1 2 3 4 5

      Check:

      $ cal 10 2013 October 2013 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

      -- Ken

Re^2: How to find first day of the first week on the month? ( strptime %Y-%j time-piece-firstlastofeverymonth.pl)
by Anonymous Monk on Sep 28, 2013 at 23:42 UTC

    Doing day math with %j which is day of year (yday)

    #!/usr/bin/perl -- ## perltidy -olq -csc -csci=10 -cscl="sub : BEGIN END" -otr -opr -ce +-nibc -i=4 -pt=0 "-nsak=*" use strict; use warnings; use Time::Piece; my $now = localtime; my $year = shift || $now->year; for my $mon ( 1 .. 12 ) { my $first = Time::Piece->strptime( qq/$year-$mon/, q/%Y-%m/ ); my $mon = $first->mon; my $yday = $first->yday; my( $last ) = grep { $_->mon == $mon } map { Time::Piece->strptime( qq/$year-$_/, q/%Y-%j/ ) } map { $yday + $_ } reverse 28 .. 31; printf '%4d %3s %02d/%02d-%02d/%02d ', $first->year, $first->month, $first->mon, $first->mday, $last->mon, $last->mday,; print "\n" if 0 == $mon % 3; } __END__ 2013 Jan 01/01-01/31 2013 Feb 02/01-02/28 2013 Mar 03/01-03/31 2013 Apr 04/01-04/30 2013 May 05/01-05/31 2013 Jun 06/01-06/30 2013 Jul 07/01-07/31 2013 Aug 08/01-08/31 2013 Sep 09/01-09/30 2013 Oct 10/01-10/31 2013 Nov 11/01-11/30 2013 Dec 12/01-12/31