Date Function Calcualate Last Sunday

[problem]

Showing the date last Sunday, using Perl.

[/problem]

[solution]

Perl has some powerful functions, to perform date manipulation. Such as strftime, localtime and mktime.

[/solution]

[example]


#!/usr/local/bin/perl

use POSIX qw(strftime);

$epoch=$^T; # you get a control T by holding down ctrl key and pressing v key, then T key.

$day=strftime "%a", localtime($epoch); # this captures the day of the week for today (Wed).
$myDate=strftime "%Y-%m-%d", localtime($epoch); # this captures the year, month and day for today

print("myDate: $myDatenday: $dayn"); # this just displays date today and day of week today, first 2 lines of output below

until($day =~ /Sun/) { # We then spin around until the day equals Sun

$epoch-=(60*60*24); # take 24 hours off our epoch
$day=strftime "%a", localtime($epoch); # calculate the day of the week for the new epoch
}

$myDate=strftime "%Y-%m-%d", localtime($epoch); # recalculate date for that epoch
print("day: $daynday: $daynmyDate: $myDaten"); # display, second 2 lines of output below

[/example]

[reference]

[tags]POSIX, strftime, localtime, Perl Coding School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

Your email address will not be published. Required fields are marked *