Reputation: 45
I have made a update on my question at Calculating date time in perl,
this is another try. the only problem i have is evaluating or comparing to have good output.
i want to output only. lets say if the minutes less than 60 or equal to 60 print minutes when others values like hours days and months are equal to 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";
}
Upvotes: 2
Views: 133
Reputation: 385789
The problem is that 2 months and 5 minutes will show as 5 minutes.
It's because you're starting with the smallest unit when you should be starting with the largest unit.
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"; }
...
Upvotes: 3