Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract days from today date and compare after

Tags:

datetime

perl

Following situation.

I have a file named 2018_12_03_FileName.log. Now I get the date from the file (2018_12_03).

I want to convert the string to a DateTime object, which works too.

$chars =~s/_//g;
$chars = Time::Piece->strptime("$chars", "%Y%m%d");
$chars = $chars->strftime("%d/%m/%Y");

Output

03/12/2018

After that I want to get the date today - 14 days. But here is one of my two problems. I tried many things, but couldn't find any real solution working for me.

my $day14 = DateTime->now();
$day14 -= (2 * ONE_WEEK);

Error:

Cannot subtract 1209600 from a DateTime object (DateTime=HASH(0x6f2d84)). Only a DateTime::Duration or DateTime object can be subtracted from a DateTime object.

Now the second problem is, I want to compare these two dates and look if the file date is in range or not.

my $cmp = DateTime->compare($chars, $day14);

Error:

Argument "15/07/2019" isn't numeric in numeric eq (==) at

A DateTime object can only be compared to another DateTime object (03/12/2018, 15/07/2019).

So how can I subtract 14 days from the today date and how can I compare these two dates after?

like image 249
poisn Avatar asked Nov 29 '25 18:11

poisn


1 Answers

You're slightly muddling up two Date/Time ecosystems that don't work well together.

You can do this using Time::Piece and Time::Seconds.

use feature 'say';
use Time::Piece;
use Time::Seconds;

my $chars = '2018_12_03';

my $tp = Time::Piece->strptime($chars, '%Y_%m_%d');

my $date14 = $tp - (2 * ONE_WEEK);

say $tp->strftime('%d/%m/%Y');
say $date14->strftime('%d/%m/%Y');

Output:

03/12/2018
19/11/2018

Or you can do it using DateTime and friends.

use feature 'say';
use DateTime;
use DateTime::Format::Strptime;

my $date_parser = DateTime::Format::Strptime->new(
  pattern => '%Y_%m_%d',
  on_error => 'croak',
);

my $chars = '2018_12_03';

my $dt = $date_parser->parse_datetime($chars);

my $date14 = $dt->clone->subtract( weeks => 2 );

say $dt->strftime('%d/%m/%Y');
say $date14->strftime('%d/%m/%Y');

Output:

03/12/2018
19/11/2018

As for your last question, you can compare either Time::Piece objects or DateTime objects using the standard Perl comparison operators (<, ==, >=, etc). But you have to compare two objects of the same type.

like image 180
Dave Cross Avatar answered Dec 01 '25 17:12

Dave Cross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!