Home > Software design >  PHP - Correctly check if a date is older than two months
PHP - Correctly check if a date is older than two months

Time:10-02

I need to set an user meta field in user meta table of wordpress. This field will contain a date, that will be set at the fisrt login of the user otherwise the field when the user register will be empty.

I'm trying with this code, but I've noticed that the date is wrong. I need to check if the date is less that 60 days or if the field is empty

<?php
$usermeta = get_user_meta( $user->ID );

if( empty($usermeta['last_pwd_reset'][0]) || $usermeta['last_pwd_reset'][0] < date('d/m/Y', strtotime(' 2 months',strtotime($usermeta['last_pwd_reset'][0]))) ){
 // other code stuff here
}  
?>

How I can correctly get the actual date in the format d/m/Y and how I can check if the date is older that two months?

My last test with the following code on phpfiddle give me a worng result

<?php
$now = '02/08/2022';

echo 'date is older than two months ' . date('d/m/Y', strtotime(' 2 months',strtotime($now)));
echo 'actual date '. date('d/m/Y');
?>
// echo results
//date is older than two months 08/04/2022
//actual date 02/10/2022

I'm doing this check into the login_redirect filter inside my custom plugin. Someone suggested me to use the wp_login action but I'm redirecting the users based on the assigned role so I'm not sure if the wp_login can fit my needings.

CodePudding user response:

So PHP seems like dates with a / be stored as an American format and dates with a - to be stored as the European format.

So a simple fix would be to simply store your $now = '02/08/2022'; as $now = '02-08-2022'; instead.

But lets say you already have all your $now dates stored they way they are, you can simple add a something like $now2 = str_replace("/","-",$now); to just programmatically do it.

Give this code a try and see if it works for you:

$now = '02/08/2022';
$now2 = str_replace("/","-",$now);

echo 'date is older than two months ' . date('d/m/Y', strtotime(' 2 months',strtotime($now2)));
echo 'actual date '. date('d/m/Y');

CodePudding user response:

I am fairly sure you are comparing 2 bits of text that happen to hold a date, that sometimes work, but it is better to make 2 dates and compare them, of in this case get the difference between the 2 dates

/*
    strings holding dates may sometimes compare as expected but more than often they will not
*/

$last_pwd_reset = '02/08/2022'; // $usermeta['last_pwd_reset'][0]
// convert to a date using correct format
$last_reset = (new DateTimeImmutable())->createFromFormat('d/m/Y', $last_pwd_reset);

$interval = $last_reset->diff(new DateTimeImmutable('now - 2 months'));
if ( $interval->days > 0 ) {
    // password needs reset
    echo 'reset password';
} else {
    echo 'no reset required';
}
  • Related