Henrique
Henrique

Reputation: 43

PHP date function giving a random number

Hello i'm making a php script to send an email on a client's birthday, basicly i'm looping through every client's birthdates and checking with today's date and if they match, an email is sent. Although the date function is giving a random number instead of today's date, the number is: 1505451600.

Maybe i'm doing something wrong in the code? Does anyone know a way to fix this?

$get_birthday = $DB_con->prepare("SELECT email, dt_nascimento FROM clientes");
if ($get_birthday->execute()) {
    while ($array_birthday = $get_birthday->fetch(PDO::FETCH_ASSOC)) {
        $birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
        // echo "</br> data:".$array_birthday['dt_nascimento'];
        // echo "</br>".$birthdate;
        $now = date("m/d");
        $now = strtotime($now);
        // echo "</br>now: ".$now;
        $email = $array_birthday['email'];
        if ($now == $birthdate) {
            include"PHPMailer/email_birthday.php";
        }
    }
}

Upvotes: 0

Views: 268

Answers (4)

Scratch Fury
Scratch Fury

Reputation: 76

There are 2 changes you need to make for your code to work:

(1) Remove this line:

$now = strtotime($now);

Reason: You don't want a timestamp. You want a formatted date.

(2) Change "m d" on this line:

$birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));

to "m/d" like so:

$birthdate = date('m/d', strtotime($array_birthday['dt_nascimento']));

Reason: you need to format $birthdate and $now the same way to make the comparison work.

Upvotes: 3

Dayron Gallardo
Dayron Gallardo

Reputation: 1640

I remove the $now conversion to timestamp and change the $birthdate format to the same as $now. This is the working code :

$get_birthday = $DB_con->prepare("SELECT email, dt_nascimento FROM clientes");
if ($get_birthday->execute()) {
    while ($array_birthday = $get_birthday->fetch(PDO::FETCH_ASSOC)) {
        $birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
        // echo "</br> data:".$array_birthday['dt_nascimento'];
        // echo "</br>".$birthdate;
        $now = date("m d");
        // echo "</br>now: ".$now;
        $email = $array_birthday['email'];
        if ($now == $birthdate) {
            include"PHPMailer/email_birthday.php";
        }
    }
}

Upvotes: 1

Iłya Bursov
Iłya Bursov

Reputation: 24146

1505451600 Is equivalent to: 09/15/2017 @ 5:00am (UTC)

this happens because:

date("m/d") returns 9/15 (today month/day)

then strtotime tries to convert this string into unix timestamp, as soon as year is not in string, current year (2017) is assumed

as soon as time part is not there, midnight in your timezone is assumed (5am utc)

this is why final time is 1505451600

Upvotes: 0

jrkirsch
jrkirsch

Reputation: 1

The reason it gives you a number is how computers measure time is the number of seconds since 1/1/1970 00:00 (UTC (Universal Time)).

Upvotes: 0

Related Questions