日期和时间计算

Date and time calculation

我已在 Calculating date time in perl

更新了我的问题

这是另一种尝试。我唯一的问题是评估或比较以获得良好的输出。

我只想输出。假设分钟小于 60 或等于 60 打印分钟,而其他值(如小时、天和月)等于 0

#!/usr/bin/perl
use Date::Parse;
use DateTime;

my $Datetime = DateTime->now;

my $date = $Datetime->mdy;   
my $time = $Datetime->hms;

my $Seen = '01/10/2022 05:22:03';
my $CurrentDateTime = "$date $time";

my $SeenDateTime = DateTime->from_epoch( epoch => str2time( $Seen ) );
my $CurrentDate_AndTime = DateTime->from_epoch( epoch => str2time( $CurrentDateTime ) );

my $diff = $CurrentDate_AndTime->subtract_datetime( $SeenDateTime );

$Min = $diff->in_units('minutes');
$Hour = $diff->in_units('hours');
$Day = $diff->in_units('days');
$Month = $diff->in_units('months');

print "Minutes: " . $diff->in_units('minutes') . "\n";
print "Hours " . $diff->in_units('hours') . "\n";
print "Days: " . $diff->in_units('days') . "\n";
print "Month " . $diff->in_units('months') . "\n";

########## PROBLEM IS DOWN HERE  ###############

if ($Seen eq $CurrentDateTime) {
print "His Online Now\n";
}

elsif ($Min <= 60) {
    print "Seen $Min Minutes Ago\n";
}

elsif ($Hour <= 24) {
    print "Seen $Hour Hours Ago\n";
}

elsif ($Day <= 30) {
    print "Seen $Day Days Ago\n";
}

elsif ($Month <= 12) {
    print "Seen $Month Month Ago\n";
}

else {
    print  "Welcome come back from moon\n";
}

问题是 2 个月零 5 分钟将显示为 5 分钟。

这是因为当你应该从最大的单位开始时,你从最小的单位开始。

my ( $years, $months, $weeks, $days, $hours, $minutes ) =
   $dur->in_units(qw( years months weeks days hours minutes ));

if    ( $years  >=  1 ) { say "Welcome back from the moon!";   }
elsif ( $months >   1 ) { say "Last seen $months months ago."; }
elsif ( $months ==  1 ) { say "Last seen 1 month ago";         }
elsif ( $weeks  >   1 ) { say "Last seen $weeks weeks ago";    }
elsif ( $weeks  ==  1 ) { say "Last seen 1 week ago";          }
elsif ( $days   >   1 ) { say "Last seen $days ago";           }
elsif ( $days   ==  1 ) { say "Last seen 1 day ago";           }
...