in reply to MySQL datetime

Obviously, the first suggestion is to do it in the database. But if you have good reasons not to do that then consider using the core module Time::Piece:

use strict; use warnings; use Time::Piece; use Time::Seconds; use Test::More tests => 2; my $last_update = ('2025-06-30 14:40:26'); cmp_ok days_since ($last_update), '<', 20, "$last_update is less than +20 days ago"; $last_update = ('2025-05-30 14:40:26'); cmp_ok days_since ($last_update), '>', 20, "$last_update is more than +20 days ago"; sub days_since { my $stamp = shift; my $tp = Time::Piece->strptime (substr ($stamp, 0, 10), '%Y-%m-%d' +); my $dayssince = (localtime() - $tp) / ONE_DAY; }

You might want to use gmtime instead of localtime depending on how you are storing the times in your DB.


🦛

Replies are listed 'Best First'.
Re^2: MySQL datetime
by joyfedl (Acolyte) on Jul 01, 2025 at 14:40 UTC

    am confused with this example, tho i want to compare from current to last update time like this way without using sub

    use strict; use warnings; use Time::Piece; use Time::Seconds qw/ ONE_DAY /; my $last_update = ('2025-06-30 14:40:26'); my current_date = localtime; if ($last_update < 20) { print "20 days havent passed\n"; } else { print "20 days have passed\n"; }

      Just construct $dayssince like I have done in the sub (you don't need a sub) and then compare that to the threshold of 20 in your code, rather than $last_update.


      🦛

        Thanks so much, i got it working like the way you have advised me

        use strict; use warnings; use Time::Piece; use Time::Seconds qw/ ONE_DAY /; my $stamp = ('2025-06-30 14:40:26'); my $tp = Time::Piece->strptime (substr ($stamp, 0, 10), '%Y-%m-%d'); my $dayssince = (localtime() - $tp) / ONE_DAY; if ($dayssince < 20) { print "20 days havent passed\n"; } else { print "20 days have passed\n"; }
Re^2: MySQL datetime
by ikegami (Patriarch) on Jul 01, 2025 at 15:14 UTC

    That factors in the time, despite instructions to the contrary

      Does it, though? So long as one is only concerned about whole days of difference (as appears to be the case for the OP) that fact that one of the stamps has a time doesn't matter.

      But if you want to be able to compare for fractional days then Line 17 should be amended to read

      my $dayssince = (localtime()->truncate(to => 'day') - $tp) / ONE_DAY;

      🦛

        My bad. Comment retracted.