Time Comparisons PHP Nightmare - php

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

Related

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

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

Odd Date("Y-m-d") result

Im having some bizarre results in regards to the php date() function. Basically Im getting a date from a Mysql database which is in a string format, split into three elements. This would be Day, Month, Year (15 september 2012 for example) Im ultimately comparing two dates to see if it has expired. But the issue is that only certain dates are allowing the code to work, and some do not work at all (or allow the if statement to work effectively) Below is my code, any help would be great.
$today = date("d-m-Y");
$expire = date("d-m-Y",strtotime($this->getData('date_day')."-".
$this->getData('date_month')."-".$this->getData('date_year'))) ;
if ($expire < $today)
{
echo 'expired';
}
else
{
echo 'Not expired';
}
Im sure its something simple, but for some reason I cannot solve it.
You need to compare the Unix timestamps.
$today = time();
$expire = strtotime($this->getData('date_day')."-".
$this->getData('date_month')."-".$this->getData('date_year')) ;
if ($expire > $today)
{
echo 'expired';
}
else
{
echo 'Not expired';
}
It looks like strtotime is expected a US date format; you need to swap the month and the day around to generate a valid date:
$today = date("d-m-Y");
$expire = date("d-m-Y",strtotime($this->getData('date_month')."-".
$this->getData('date_day')."-".$this->getData('date_year'))) ;
On the other hand, see Stephen305's answer - it's a much better solution to your problem.

Comparing a date to current server date using PHP

I am using the following code to attempt to compare the current date with a date entry in a mySql database. It's code that I have found online and adapted as all the examples I have found hard-code the date to compare the current date with.
The trouble is even dates in the future are being marked as expired and I can't understand why this would be.
I am afraid that I am still new to PHP, so I may be making a schoolboy error!
$exp_date = KT_formatDate($row_issue_whatson1['dateToShow']);
$todays_date = date("d-m-Y");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) { echo "Not expired"; } else { echo "expired"; }
Any help would be most appreciated.
I should add that the date time format used in the database entries is dd/mm/yyyy
Instead of making a string then converting it to a timestamp, simply use mktime:
<?php
$today = mktime(
0, // hour
0, // minute
0 // seconds
);
?>
The rest of the values will be filled according to today's date. If this still gives problems, put in some echo's for the values of $exp_date and $expiration_date.
Edit
Since this solved the problem, the discrepancy you were seeing was because you were doing the opposite with date('d-m-Y'). You were asking for the current date and the time values are then filled in with the current time. The expiration date in the database is likely set at midnight. With both dates being equal, and it being say 11am now, you are comparing if (00:00:00 > 11:00:00) which fails.
$exp_date = 14/05/2011 // todays date, int
$server_date = server.date() // servers date, int
// check exp_date against server date
if ( $server > $exp_date)
{ echo "Sorry your 'service' has expired"; }
else
{ echo "Welcome 'members_name' to StackOverflow"; }
Try that. However you need the right date format, as server.date() is probably different in PHP.
If problem still persists I would check whether your dates are strings or integers or both. That could possibly be the issue.
Hope that helps.
DL.
Your function does not seem to be valid.
function KT_formatDate( $exp_date){
$exp_date = strtotime($exp_date);
$now = time();
if ($now > $exp_date)
return 'expired';
else
return ' Not expired';
}
$response = KT_formatDate($row_issue_whatson1['dateToShow']);

Categories