Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: code to get the date for "next Thursday"

by Albannach (Monsignor)
on Mar 20, 2006 at 21:08 UTC ( [id://538048]=note: print w/replies, xml ) Need Help??


in reply to code to get the date for "next Thursday"

Again it might not be any faster, but it is useful to note that ParseDate is smarter than you think:

Use Date::Manip; print UnixDate(ParseDate('next thursday'),'%A %e %b %Y'),"\n";

gives Thursday 23 Mar 2006

Update: Here's a method using the usually-faster Date::Calc and a benchmark of some of the offerings... any guesses as to why Date::Manip is soooo slow? (1.7GHz P4 Win2k, 256MB RAM)

Rate Manip bfdi ikegami Calc Manip 216/s -- -7% -99% -100% bfdi 231/s 7% -- -99% -100% ikegami 29540/s 13596% 12701% -- -65% Calc 84063/s 38874% 36327% 185% --

Code follows:

use strict; use warnings; use Benchmark qw(cmpthese); use Date::Manip; use Date::Calc qw(Today Day_of_Week Add_Delta_Days); Date_Init('TZ=EDT'); # for ikegami use POSIX qw( strftime ); use Time::Local qw( timegm_nocheck ); sub ikegami { my ($day, $mon, $year, $wday) = (localtime())[3..6]; # Defaults to +now. $year += 1900; $day += (7 - $wday + 4) % 7; my $next_th = timegm_nocheck(0,0,0,$day,$mon,$year); # fixed, was $m +day rather than $day return strftime('%Y-%m-%d', gmtime($next_th)); } sub bfdi533 { my $today_dt = &ParseDate("today"); my $new_dt = &Date_GetNext($today_dt, 'Thu', 1); my $date = &UnixDate($new_dt, "%Y-%m-%d"); } sub Manip { return UnixDate(ParseDate('next thursday'),'%Y-%m-%e'); } sub Calc { my($year,$month,$day) = Today(); my $nextday = 4; # Thursday my $dow = Day_of_Week($year,$month,$day); my $delta = (7 + $nextday - $dow) % 7; my ($y,$m,$d) = Add_Delta_Days($year, $month, $day, $delta); return sprintf('%4i-%02i-%02i', $y, $m, $d); } cmpthese(-3, { bfdi => \&bfdi533, ikegami => \&ikegami, Manip => \&Manip, Calc => \&Calc, } );

--
I'd like to be able to assign to an luser

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://538048]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-04-23 07:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found