I am trying to check if in a database the time of a row and a certain column is older then today then to echo success but it is echoing success for a date which is tomorrows!
Code
// Set variable for the time
$timenow = date('l jS \of F Y h:i:s A');
// Start Expired password check and drop function
function cronexec_expired ($timenow) {
include('../../config.php');
// Open up a new MySQLi connection to the MySQL database
mysql_connect($dbHost, $dbUsername, $dbPassword);
mysql_select_db($dbTable);
// Query to check the status of the code input
$expiry_check = "SELECT * FROM code_log WHERE status='Unused'";
// Run the query
$expiry_checkexec = mysql_query($expiry_check);
while($expiry_possibles = mysql_fetch_array($expiry_checkexec)) {
echo $expiry_possibles[6] . '<br /><br />';
echo $timenow . '<br /><br />';
if (date('l jS \of F Y h:i:s A', strtotime($expiry_possibles[6]) < $timenow)) {
echo "Success";
}
}
}
$expiry_possibles[6] value
Monday 9th of September 2013 12:46:20 PM
Time Now
Sunday 8th of September 2013 01:35:22 PM
Any advice would be appreciated
I don't see why you are using a full length date, there is no need. Instead how about using the unix timestamp? See http://php.net/manual/en/function.time.php. The comparison might be having a hard time comparing a full date string?
I've always found it a lot easier to use time() as its basically comparing two numbers.
$current_time = time();
$expiry_possibles_timestamp = strtotime($expiry_possibles[6]);
if ($current_time > $expiry_possibles_timestamp)
{
// Older than current time
}
I've modified your code below, try that out. Bear in mind you will need PHP 5.3 and above.
function cronexec_expired($timenow)
{
include('../../config.php');
// Open up a new MySQLi connection to the MySQL database
mysql_connect($dbHost, $dbUsername, $dbPassword);
mysql_select_db($dbTable);
// Query to check the status of the code input
$expiry_check = "SELECT * FROM code_log WHERE status='Unused'";
// Run the query
$expiry_checkexec = mysql_query($expiry_check);
while ($expiry_possibles = mysql_fetch_array($expiry_checkexec))
{
echo $expiry_possibles[6] . '<br /><br />';
echo $timenow . '<br /><br />';
$datetime = DateTime::createFromFormat('l jS \of F Y h:i:s', $expiry_possibles[6]);
if (!$datetime) continue; // Skip this execution as we cannot parse the date, so we will not trust it.
if (time() > $datetime->getTimestamp())
{
echo "Database row is in the past";
} else
{
echo "Database row is in the future";
}
}
}
That should work, although I have not tested it. How is the date stored in the database? It should be in MySQL format (YYYY-MM-DD HH:MM:SS) or in a unix timestamp format.
I recommend using the DateTime and DateInterval classes.
You can them compare if the difference is, say, exactly one day:
$expiry = new DateTime($expiry_possibles[6]);
if ($expiry->diff($time_now)->format('%d') == "1") ...
Or vice versa. There is also a procedural interface for this in the form of date_diff()
More info:
http://www.php.net/manual/en/datetime.diff.php
Related
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
i am using following codes to get current time on server as per timezone parameter but i am getting wrong output. About 10/20 minutes delay then server time. And it also not gets updated. How to solve it? any idea?
<?php
function server_time_as_per_users_zone($users_zone){
$dateTime = new DateTime('now', new DateTimeZone($users_zone));
$r = $dateTime->format("d-m-Y h:m A");
return $r;
}
echo server_time_as_per_users_zone("Asia/Dhaka");
You are using a wrong format mask. The m stands for month number and not minutes.
Change it to
function server_time_as_per_users_zone($users_zone){
$dateTime = new DateTime('now', new DateTimeZone($users_zone));
$r = $dateTime->format("d-m-Y h:i A");
return $r;
}
echo 'UTC - ' . server_time_as_per_users_zone("UTC").PHP_EOL;
echo 'Europe/London - ' . server_time_as_per_users_zone("Europe/London").PHP_EOL;
echo 'Asia/Dhaka - ' . server_time_as_per_users_zone("Asia/Dhaka").PHP_EOL;
RESULT:
UTC - 19-04-2017 05:40:23 PM
Europe/London - 19-04-2017 06:40:23 PM
Asia/Dhaka - 19-04-2017 11:40:23 PM
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>';
I have an Android app which is used to store data of users in MySQL database using PHP. I need to do some validations according to the date.The MySQL Database has a predefined date for each user.The date increases by 1 day whenever a user inserts data twice for that day.And when the date exceeds the current date,it shows a message that "the user has already submitted data for the day".
My PHP file is :
<?php
require "conn.php";
$user_mobile = $_POST["mobile_num"];
$user_pass = $_POST["password"];
$mysql_qry = "select * from employee_data where mobile like '$user_mobile' and password like '$user_pass';";
$result = mysqli_query($conn,$mysql_qry);
if(mysqli_num_rows($result) > 0 ) {
$row = mysqli_fetch_assoc($result);
$name= $row["name"];
$_POST['user'] = $name;
$last_updated = $row["last_updated_date"];
$_POST['user'] = $name;
$_POST['date'] = $last_updated;
echo "Login successful. Welcome_" .$name;
echo "_Date:" .$last_updated;
$now = new DateTime("Asia/Kolkata");
$n = ($now->format('Y-m-d'));
if(($last_updated > $n)) {
echo "exceeded";
}
?>
But what is happening is if "$last_updated"(the date which is changing everytime) is the current date,then it is not going inside the if condition. So if "$last_updated" is today's date, then the user gets the message "the user has already submitted data for the day". I tried doing an echo of "$n" and it gives the current date. So, it should not go to the if-condition because ($last_updated == $n) . But its going inside the if-condition when ($last_updated == $n).I don't know why this is happening.Can anyone please help me with this?
Try to change your
$now = new DateTime("Asia/Kolkata");
to:
$now = new DateTime(null, new DateTimeZone('Asia/Kolkata'));
You need to compare them as objects.. Try something like this..
$now = new DateTime("Asia/Kolkata");
if (new DateTime($last_updated) > $now) {
echo "exceeded";
}
I'm not sure if your timezones are set properly on your server but to be sure you could do one of the following as well..
$now = new DateTime('Asia/Kolkata');
if (new DateTime($last_updated, new DateTimeZone('Asia/Kolkata')) > $now) {
echo "exceeded";
}
Or probably even better..
date_default_timezone_set('Asia/Kolkata');
$now = new DateTime('now');
if (new DateTime($last_updated) > $now) {
echo "exceeded";
}
Your issue is that since you are not keeping the time in the database and when you compare the date with now which includes the time, the now will always be greater than the date you pull from the database.
The database time 2017-03-17 becomes 2017-03-17 00:00:00 php time.
When you generate php now time it will be 2017-03-17 xx:xx:xx which will always be greater than database time
$last_updated = new DateTime($row["last_updated_date"],new DateTimeZone("Asia/Kolkata"));
$today = new DateTime('now',new DateTimeZone("Asia/Kolkata")); //gets current date time
$today->setTime(0,0); // back to the beginning of the day
//echo $last_updated->getTimestamp . | . $today->getTimestamp; // for debugging purpose
if(($last_updated->getTimestamp >= $today->getTimestamp)) {
// note that I have used '>=' to allow the current date
}
You can also use the DateTime->diff() function.
Reference: http://php.net/manual/en/class.datetime.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)){