PHP date function giving a random number - php

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";
}
}
}

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.

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";
}
}
}

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)).

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

Related

PHP Checking if outputted date is less than current date

I have the following function which works well but would like to check the returned date and compare with the current date if before current date to show something if current or in future show as normal.
Function:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
Call:
echo '<li class="list-group-item">Support Expires: ' . dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60 . '</li>');
Output:
2nd March 2016
So as not today's date and/or before today's date would like to echo a message, else just show the date.
In PHP it is very simple to compare two different dates using < = > like you normally compare numbers. The only step prior to this is below:
//Tell PHP that the value in variable is a date value
$date_1 = date_create("2017-05-29"); //This value can be any valid date format
date_1_formatted = date_format($date_1, "Y-m-d"); //This formats the date_1
//Now you can simply put the second date, for example, today.
$date_2 = date_create("2017-04-29"); //This value can be any valid date format
date_2_formatted = date_format($date_2, "Y-m-d"); //This formats the date_1
//For current date, it is simpler
$date_today_formatted = date("Y-m-d");
//Now you can compare these two dates easily
if ($date_1 < $date_today_formatted) {
echo "Date 1 falls before today.";
}
else {
echo "Date 1 falls after today.";
}
Hope this helps!
I managed to work it out using the following 2 functions:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
function checkLicenceSupport($licence_date) {
$date_now = new dateTime();
$date_set = dateFormat($licence_date, 11*60*60);
if ($date_now > $date_set) {
return 'date expired';
} else {
return 'date valied';
}
}
I have the following function which works well, but would like to
check the returned date and compare with the current date.
If it is before the current date, show something.
If it is the current date, or in future, show as normal.
I needed to rewrite your question, because lack of grammar and punctuation made it confusing. No offense intended.
Your call code has the closing parenthesis for your function call is placed wrongly.
dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60)
It is more readable to use full days or hours (in seconds):
11*86400 //(11 Days);
11*3600 //(11 Hours);
The function and code, as you have it now, will always return a date in the future of the date you've submitted via the call. (I can't tell from your question whether this was intended or not).
Currently, there is no "comparison" in your function. But your question indicates you want to compare the submitted date to the current date and then do something in certain cases.
If you are going to use a Unix timestamp, then there's no need for multiple formatting, compare the two dates in Unix, then format the result.
function dateCompare($submittedDate){
//This is only needed if your submitted date is not a unix timestamp already
$submittedDate = strtotime($submittedDate);
$currentDate = time(); // Creates timestamp of current datetime
if($submittedDate < $currentDate) {
//show something i.e. return "Support Has Expired";
}else {
return date('jS F Y', $submittedDate);
}
}
echo '<li class="list-group-item">Support Expires: '.dateCompare($purchase_data['verify-purchase']['supported_until']).'</li>';

Comparing two dates in PHP and MYSQL

I want to compare two dates and time values in PHP. One date is coming from MySQL, and second one is the current date. I want to run some code when both dates are the same. I tried the code below, but condition satisfies any time which is wrong.
$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
//I want to run some code here
}else{
}
What is wrong with the code? I also tried to covert both dates with strtotime() before comparing, but it gave me the same issue. The above condition satisfies any time even if both dates are different.
Try this :
$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if(strtotime($current_datetime) == strtotime($send_date)){
//I want to run some code here
}else{
}
Hope it helps !!!!
One way is to fetch the Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) from MySQL, then operate on the numbers:
$row = get_db_row("SELECT UNIX_TIMESTAMP(send_date) AS send_date_ts
FROM table WHERE $condition");
$hours = (int) ($row['send_date_ts'] / 3600);
$current_hours = (int) (time() / 3600);
if ($hours == $current_hours) {
// current hour
}
Timestamps are convenient because:
there is no need to take the format into account;
operations on numbers are usually faster;
the code looks cleaner.
Try this. On my server is working just great I've got something else because they aren't equal. Date which I receive from database is type datetime format 2015-04-13 09:03:49
<?php
$current_datetime = strtotime(date('Y-m-d H:i'));
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
//I want to run some code here
echo 'something';
}else{
echo 'something else';
}
Output:
echo $current_datetime . '<br/>';
2016-10-17 09:19
echo $send_date .'<br/>';
2015-04-13 09:03
// result
something else

Check if date expression ("d-m" without leading zeros) is today

I want to compare current date's day and month with subscription date's day and month only.
For example:
current date(d-m) = 3-6
And I want compare it with any other d-m
How should I do it in PHP
In my project condition is like birth date in which we don't compare year.
The trick in this is to let the month come first. This way PHP can compare the numbers by highest value. Take a look at the following example:
$aDate = DateTime::createFromFormat('m-d', '05-20');
$bDate = DateTime::createFromFormat('m-d', '06-29');
if ($aDate->format('md') > $bDate->format('md')) {
echo "'aDate' is bigger than 'bDate'";
}
use like
$current_date = date("d-m");
$subscription = "03-06-2016";
$subscription_date = date("d-m", strtotime($subscription));
if($current_date ==$subscription_date)
{
echo "date is equal";
}else
{
echo "date is not equal";
}
If you only need to check if the j-n date is the same as the current date, then you don't need to make more than one function call. Because you are not comparing greater than or less than, the format of your input is unimportant.
Code: (Demo)
$subscription = '29-11';
var_export(date("j-n") === $subscription);
// at the moment, the result is true
j is today's day of the month without any leading zeros and
n is today's month without any leading zeros.
Use DateTime() PHP objects.
Considering you have an array with user info from mysql query result: ($userData['suscriptionDate'])
$today = new DateTime();
$userSuscription = new DateTime($userData['suscriptionDate']);
if ( $today->format('d') == $userSuscription->format('d') && $today->format('m') == $userSuscription->format('m')) {
echo 'Congratulations!!';
}
Use DATE_FORMAT() function to extract part of date:
Ref: http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format
SELECT * from table_name WHERE DATE_FORMAT(subscription_date, '%d-%m') = "05-05";
I think, more elegant way to compare, especially when you have a full date with time is diff function of Datetime class:
$d1 = new Datetime();
$d2 = new Datetime('+3 months +2 days +3 hours');
$diff = $d1->diff($d2);
var_dump($diff->d); // 2
var_dump($diff->m); // 2
// or have a comparison as a string
var_dump($diff->format('Difference is in %R%a days'));
// output: Difference is in 63 days
Enjoy! Link to doc
This may help you
$sdate = $row['subscription_date'];
$date1 = date("m-d");
$date2 = date("m-d",strtotime($sdate)) ;
if ($date1 == $date2) {
}

Time Comparisons PHP Nightmare

I'm having an issue with time comparisons with PHP - I think I must be doing something stupid but I've been trying different things for hours now and I'm just hitting a brick wall.
I'm pulling data from EVE's API and then doing a check for whither there is still subscription there and whither there is a skill in training - with both of these there is a particular time frame (1 week for subscription and 12 hours for skills) that I'd like to flag up a warning - however I can't seem to get it working at all. The output of all the dates and times seems to be the right format I just can't get the comparison to work.
I'm wondering if anyone can point what's most likely my stupid mistake and give me a push in the right direction.
thanks for taking a look,
<?php
// ---- For Skill Queue
$apiSection = "char/SkillQueue";
$urlChar = "https://api.eveonline.com/$apiSection.xml.aspx?keyID=$keyID&vCode=$vCode&characterID=$charID";
$data = file_get_contents($urlChar);
$xml = new SimpleXMLElement($data);
foreach ($xml->result->rowset->row as $row){
$charQueueEndTemp = $row{'endTime'};
}
$charQueueEnd = date("d-m-Y H:m", strtotime($charQueueEndTemp));
//echo "Skill Test" . $charQueueEnd;
// --- Account API
$apiSection = "account/AccountStatus";
$urlAccount = "https://api.eveonline.com/$apiSection.xml.aspx?keyID=$keyID&vCode=$vCode";
$data = file_get_contents($urlAccount);
$xml = new SimpleXMLElement($data);
$accSubsTemp = $xml->result->{'paidUntil'}->{0};
$accSubs = date("d-m-Y H:m", strtotime($accSubsTemp));
date_default_timezone_set('Europe/Paris');
$currentDate = date("d-m-Y H:m");
$lessWeek = date("d-m-Y H:m", strtotime("-1 week"));
$plusWeek = date("d-m-Y H:m", strtotime("+1 week"));
$plus12Hour = date("d-m-Y H:m", strtotime("+12 hour"));
//Date Tests
//echo "</br> Curent Date: ".$currentDate;
//echo "</br> Plus Week: ".$plusWeek;
//echo "</br>Acc Subs: ".$accSubs;
//echo "</br>Acc +12: ".$plus12Hour;
// -- Account Subscribed Check
if($currentDate > $accSubs){
echo "Account is not Subscribed";
}
elseif($plusWeek > $accSubs){
echo "Account has less than 1 week Subscription";
}
else{
echo "Account is Subscribed";
}
// -- Skill Training Check
if($charQueueEnd = null){
echo "Skill Queue Ended";
}
elseif($plus12Hour > $charQueueEnd){
echo "Skill Queue ending in less than 12 Hours";
}
else{
echo "Skill Queue Active";
}
?>
Start using DateTime class for date/time manipulation/compare :
If you change your code to this :
$currentDate = new DateTime();
$lessWeek = new DateTime("-1 week");
$plusWeek = new DateTime("+1 week");
$plus12Hour = new DateTime("+12 hour");
... then your IF statements will start to work.
You are doing the date comparisons completely WRONG. You're comparing date STRINGS, e.g. using some dates formatted the same way you're doing:
$plusWeek = '26-08-2013 8:30'; Aug 26th, 2013
$accSubs = '9-08-2013 10:45'; Aug 9th, 2013
Since these are strings, string comparison rules apply. That means the strings are compared character by character, and (string)26 is actually LESS than string(9), because 2 is smaller than 9.
You need to keep things as the raw timestamps, e.g. the strtotime() output:
$plusWeek = strtotime('2013-08-26 08:30'); // 1377527400
$accSubs = strtotime('2013-08-09 10:45').; // 1376066700
Comparing these integer values will work as you want.
The main problem is also that you're not formatted your data strings in "most significant data" order. If they were formatted with the year first, e.g.
yyyy-mm-dd hh:mm:ss
then a string comparison WOULD work as a side effect.
If you want to compare dates you have to compare arguments returned by strtotime() function, for example:
elseif(strtotime($plus12Hour) > strtotime($charQueueEnd)){

Issues converting MySQL datetime with PHP's date function

I'm trying to use PHP to convert some of my database's datetime entries so that they appear with the full month name, day, and year: ex. July 08 2011
The entries in the database all have the correct dates and times, but when I try converting them, they show up in the correct format but the day becomes the month (08 shows up as August), the day shows up as the year (11), and the month shows up as the year (July shows up as 2007). So July 08 2011 gets converted to August 11, 2007.
Code:
$date2 = date('F j Y', strtotime($date));
Anyone know what might be up?
var_dump($date):
string(14) "07-07-11 01:32"
More code:
while($get_row = mysql_fetch_array($get_rs)) {
$gb_str2 .= $tableOpen;
$name = $get_row["Name"];
$email = $get_row["Email"];
$comment = $get_row["Comment"];
$date = $get_row["Date"];
if(!empty($name)) {
// If name exists and email exists, link name to email
if(!empty($email)) {
$name="by $name";
}
// If name does exist and email exists, link email to email
} elseif (!empty($email)) {
$name = "by $email";
// Else make name blank
} else {
$name = "";
}
// Append to string we'll print later on
$date2 = date('F j Y', strtotime($date));
$gb_str2 .= "$comment<hr>< posted on $date2 $name>".$tableClose."<br>";
}
For some reason,
$date = date('F jS Y', strtotime($get_row['date']));
did the trick. I still don't really understand what was going wrong.

Categories