Calculating date time in perl
am new to perl am trying to do a script which can check
last seen / days / hours and minutes
i have made some try.
but i need help to make it function well
#!/usr/bin/perl
use DateTime;
my $Datetime = DateTime->now;
my $date = $Datetime->ymd;
my $time = $Datetime->hms;
$Seen_time = "11:50:02";
$Seen_day = "2022-01-12";
if ($Seen_time eq $time) {
print "His Online\n";
}
elsif ($Seen_time ne $time) {
# calculate how many minutes has passed from current time and seen time
print "He was online 3 minutes or hours back\n";
}
elsif ($Seen_day) {
# calculate days from date
print "he was online 2 days back\n";
}
else {
print "we are going to moon soon\n";
}
Here is a very rough implementation using DateTime::Format::Human::Duration https://metacpan.org/pod/DateTime::Format::Human::Duration as Håkon Hægland suggested, you will need to fine tune the output:
#!/usr/bin/perl
use DateTime;
use warnings;
use strict;
use diagnostics;
use DateTime::Duration;
use DateTime::Format::Human::Duration;
my $Datetime = DateTime->now;
my $Seen_time = "11:50:02";
my $Seen_day = "2022-01-12";
# You probably need to take the above and get it in a DateTime object this is just for the example:
my $seen = DateTime->new(year => 2022, day => 12, month => 1, hour => 11, minute => 50, second => 2);
#you could use the DateTime->compare method to compare two DateTime objects. The semantics are compatible with Perl's sort function;
#it returns -1 if $seen < $Datetime etc.
my $cmp = DateTime->compare( $seen, $Datetime );
if (!$cmp) {
print "He is Online\n";
}
elsif ($cmp == -1) {
my $d = DateTime::Duration->new();
my $span = DateTime::Format::Human::Duration->new();
my $dur = $Datetime - $seen;
# You can fine tune this output to just me hours or whatever:
print "He was online " . $span->format_duration($dur) . " ago \n";
}
else {
print "We are going to moon soon\n";
}