How do I get last year date and current date using perl? - perl

I want to fetch current date and exactly last year date using perl in the format of 140220 and 130220.

Perhaps the following will help:
use strict;
use warnings;
use Time::Piece;
my $time = Time::Piece->new;
my $currDate = $time->strftime('%y%m%d');
print $currDate, "\n";
my $lastYear = $time->add_years(-1)->strftime('%y%m%d');
print $lastYear;
Output:
140219
130219

Here is a sample using DateTime.
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;
use DateTime;
my $dt = DateTime->now();
my $year_ago = DateTime->now()->subtract(years => 1);
say $dt->strftime("%y%m%d");
say $year_ago->strftime("%y%m%d");

Related

Perl: Getting weeknumbers from pre-formatted date-time strings

I am getting date-time strings in the format "2021-04-25 04:27:35" (YYYY-MM-DD hh:mm:ss) and need to convert them to "2021w18".
I must get the weeknumber and I already have the below in my perl script.
use Time::Piece;
use POSIX qw(strftime);
Any help will help me progress beyond "newbie".
Here's a subroutine that will do what you want:
use Time::Piece;
use POSIX qw(strftime);
use strict;
use warnings;
use feature 'say';
sub dateToWeek {
my ($date) = #_;
my $t = Time::Piece->strptime($date, "%Y-%m-%d %H:%M:%S");
return $t->strftime("%Yw%U");
}
say dateToWeek("2021-04-25 04:27:35");
Output:
2021w17
Pass it a date contained in a string and it will return the year + "w" + week number.
If you need it to return 2021w18 instead of 2021w17 for April 25, 2021, change the return statement to add 1 to the strftime like so:
return $t->year . "w" . ($t->strftime("%U")+1);

Get Time From String - Perl

In php you could just do
strtotime("+1 days");
And get the machine time for the next day.
I want to try the same with Perl, I'm going to be doing a sort of cron job to execute certain methods.
I know you could it use str2time from the module http://search.cpan.org/~gaas/HTTP-Date-6.02/lib/HTTP/Date.pm I just can't seem to figure it out.
I tried the following, but I'm unsure if I did it right
use HTTP::Date qw(str2time);
use Time::Piece;
use Time::Seconds;
my $lol = localtime();
my $time = $lol - ONE_HOUR*($lol->hour + 24);
print "Time: " . str2time($time);
use Time::Piece;
use Time::Seconds;
my $t1 = localtime() + ONE_DAY;
print $t1->epoch;
Tool for the job here is Time::Piece.
#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;
my $this_time = localtime();
print $this_time + 60*60*24,"\n";

Date formatting in Perl

I have a variable which contain value "20140720". I need to change it to the format "20/07".
My code is shown below.
#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;
my $date = '20140720';
my $date_format = Time::Piece->strptime($date, '%d/%m');
my $new_date = $date_format->strftime('%d/%m');
print $new_date;
I get following error during execution.
Error parsing time at /usr/lib/perl5/5.10.0/x86_64-linux-thread-multi/Time/Piece.pm line 470.
In this line — Time::Piece->strptime($date, '%d/%m'); — you specified the format that $date is currently in incorrectly. The second argument describes how the string should be parsed, not the format you want it to be in (which is what the following line is for).
Use '%Y%m%d' instead.
With a fixed string, you should use the pack/unpack function:
use strict;
use warnings;
my $date = '20140720';
my (undef, $m, $d) = unpack 'A4A2A2', $date;
print "$d/$m";
If you don't need further date processing, using a simple regular expression may be simpler:
use strict;
use warnings;
my $date = '20140720';
my $new_date = $date;
$new_date =~ s!\d{4}(\d{2})(\d{2})$!$2/$1!;
print $new_date, "\n";

Perl Test::MockTime + Time::localtime

I'm trying to replace current time with Test::MockTime module. It works fine:
use Test::MockTime qw(:all);
use Time::Local;
my $sec = 0;
my $min = 0;
my $hour = 14;
my $mday = 1; #1-31
my $mon = 1; #1-12
my $year = 2013; #1970-...
set_fixed_time(timelocal($sec,$min,$hour,$mday,$mon-1,$year-1900));
print join "\n", localtime;
But, when I use Time::localtime, nothing happens:
use Time::localtime;
use Time::Local;
use Test::MockTime qw(:all);
my ($sec,$min,$hour,$mday,$mon,$year)=(0,0,14,1,1,2013);
set_fixed_time(timelocal($sec,$min,$hour,$mday,$mon-1,$year-1900));
my $t=localtime();
my $xmon=$t->mon;
my $xyear=$t->year;
my $xday=$t->mday;
my $xmon_now=$xmon+1;
my $xyear_now=$xyear+1900;
print "$xmon_now $xyear_now\n";
The output will be "12 2012"
How can I change time in my tests when Time::localtime is used?
Thanks and sorry for my English
UPD:
use Time::localtime;
use Test::MockTime qw(:all);
didnt work
use Test::MockTime qw(:all);
use Time::localtime;
works fine) perl magic
Test::MockTime overrides localtime, but Time::localtime uses CORE::localtime (the unoverrided version of localtime). You'd have to rewrite Time::localtime's localtime.

Today's Date in Perl in MM/DD/YYYY format

I'm working on a Perl program at work and stuck on (what I think is) a trivial problem. I simply need to build a string in the format '06/13/2012' (always 10 characters, so 0's for numbers less than 10).
Here's what I have so far:
use Time::localtime;
$tm=localtime;
my ($day,$month,$year)=($tm->mday,$tm->month,$tm->year);
You can do it fast, only using one POSIX function. If you have bunch of tasks with dates, see the module DateTime.
use POSIX qw(strftime);
my $date = strftime "%m/%d/%Y", localtime;
print $date;
You can use Time::Piece, which shouldn't need installing as it is a core module and has been distributed with Perl 5 since version 10.
use Time::Piece;
my $date = localtime->strftime('%m/%d/%Y');
print $date;
output
06/13/2012
Update
You may prefer to use the dmy method, which takes a single parameter which is the separator to be used between the fields of the result, and avoids having to specify a full date/time format
my $date = localtime->dmy('/');
This produces an identical result to that of my original solution
use DateTime qw();
DateTime->now->strftime('%m/%d/%Y')
expression returns 06/13/2012
If you like doing things the hard way:
my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon) == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";
use Time::Piece;
...
my $t = localtime;
print $t->mdy("/");# 02/29/2000
Perl Code for Unix systems:
# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;
# Remove newline character
$current_date = substr($current_date,0,-1);
print $current_date, "\n";
Formating numbers with leading zero is done easily with "sprintf", a built-in function in perl (documentation with: perldoc perlfunc)
use strict;
use warnings;
use Date::Calc qw();
my ($y, $m, $d) = Date::Calc::Today();
my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
print $ddmmyyyy . "\n";
This gives you:
14.05.2014