Date Function Calcualate Last Sunday

Problem

Showing the date last Sunday, using Perl.

Solution

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

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 epochprint("day: \$daynday: \$daynmyDate: \$myDaten"); # display, second 2 lines of output below`

Reference

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