in reply to Re: Is there an easy way to get the start date of the current week?
in thread Is there an easy way to get the start date of the current week?

I just wrote another message in which I mention rarely using the components from list-context localtime(), except to feed into strftime(). This is one of those rare situations which call for using the components. In scalar context, localtime() gives you a fully formatted date-time string, but in list context it returns:

my ( $seconds, $minutes, $hours, $day_of_month, $month_idx, $years_since_1900, $day_of_week_number, $day_of_year, $id_dst ) = localtime($now);
So rather than generating a date string "Sat Aug 21 22:00:53 2010" and then parsing it with a regex ( not even substr()! .. shocking! ), why not use the day of the week component .... 0 == Sunday through to 6 == Saturday.
$now -= 43200 while (localtime($now))[6]; # count back half days till +Sunday

--
TTTATCGGTCGTTATATAGATGTTTGCA

Replies are listed 'Best First'.
Re^3: Is there an easy way to get the start date of the current week?
by BrowserUk (Patriarch) on Aug 22, 2010 at 03:02 UTC
    So rather than generating a date string "Sat Aug 21 22:00:53 2010" and then parsing it with a regex ( not even substr()! .. shocking! ), why not use the day of the week component

    How many times do you need to calculate 'last sunday' in any given run of a program?

    I think that if you are doing it more than once, you've programmed an error. Even if the run transitions midnight, using two different definitions of that term within a single run of the program, is likely to be an inconsistency with ramifications.

    On that basis, you should only calculate it once. And so the performance gain of only taking 3 milliseconds over 6 is neither here nor there.

    Even if you do the sensible thing and (having obtained the day of week) perform a calculation rather than a loop:

    sub lastSunday2 { my $now = time; my @now = localtime $now; return $now -= ( $now[ 6 ] * 2 - 1 ) * 43200; }

    And so cut the cost of that single call to 1 millisecond, you're still never going to notice it.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.