Home > Net >  How to get date of two month old date from current date
How to get date of two month old date from current date

Time:08-24

I am trying to pull data (some transaction related data) from DB. To pull the data, I am passing start date and end date as an argument to the query.

Here I need to pull the data of last 2 months. i.e., Start time would be Jun 01, 2022 and End time would be Aug 01, 2022.

Below is the script:

#!/usr/bin/perl

use strict; 
use warnings;
use DateTime;
use Date::Format;
use Date::Parse;

my $nowdate = DateTime->now(time_zone => 'local');
my ($month, $year) = ($nowdate->month, $nowdate->year);

my $date = DateTime->new(
                year => $year,
                month => $month,
                day => 1,
        );
my $end_time = str2time($date);
print "END:$end_time\n";
print time2str("%d-%m-%Y %T", $end_time)."\n"; #printing just to see in human readable format

my $start_time = $date->clone;
$start_time->add( months => 1 )->subtract( days => 92 );
$start_time = str2time($start_time);
print "START:$start_time\n";
print time2str("%d-%m-%Y %T", $start_time)."\n"; #printing just to see in human readable format

I have two issues over here:

  1. I am using DateTime object two times to get end time. Can it be done in one shot?
  2. $start_time->add( months => 1 )->subtract( days => 92 ); In this line of code, I have to explicitly mention subtract 92 days, which wouldn't be right always. Since some months have 30 days or 31 days or even 29 days. How can I get 2 month's beginning day date?

Another example: Lets assume if we are in September 2022, then Start time and End time would be Jul 01, 2022 and Sep 01, 2022 respectively.

Note: Perl version is 5.16.3

It would be good If I can do it with Core modules which comes with 5.16.3

CodePudding user response:

You could simplify it by using truncate(to => 'month') to get to the first in the current month:

my $end = DateTime->now(time_zone => 'local')
                  ->truncate(to => 'month');

This may however fail on a day without a midnight so this may be an option:

my $end = DateTime->now(time_zone => 'local')
                  ->set_time_zone('floating')
                  ->truncate(to => 'month');

Then subtract the number of months to get the start date:

my $start = $end->clone->subtract( months => 2 );

Then:

my $start_time = str2time($start);
my $end_time = str2time($end);

print "START:$start_time\n";
print time2str("%d-%m-%Y %T", $start_time)."\n";

print "END:$end_time\n";
print time2str("%d-%m-%Y %T", $end_time)."\n";

Possible output:

START:1654034400
01-06-2022 00:00:00
END:1659304800
01-08-2022 00:00:00
  • Related