PHP Checking if outputted date is less than current date - php

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>';

Related

If a Date exist return a calculated date

I have the code below to add days to a date.
$date = '[[lbc_dates_lbc_date]]';
$date = date('d F y', strtotime('+28 days', strtotime($date)));
echo $date;
This works perfectly for cases where a date entry actually exists, however, it's displaying an odd date for cases where date entry doesn't exist yet (blank).
Can you amend the code to say if a date exists add days, otherwise leave blank?
Please see image attached (errors in red, correct view in green)
Thanks
strtotime() will return FALSE when it can't parse the date. This is being treated as 0, the epoch time, when you use it as the base time in the second call to strtotime().
Check for that before trying to use the result.
$parsed = strtotime($date);
if ($parsed) {
$date = date('d F y', strtotime('+28 days', $parsed));
} else {
$date = '';
}
You should use DateTime object for storing and manipulating dates.
echo $date !== null ? (new DateTime($date))->add(new DateInterval('P28D'))->format('Your date format here') : '';
https://www.php.net/manual/en/class.datetime.php
Basically it uses a ternary operator to check if $date is null, if it's not, it creates a new DateTime object for the current date, adds 28 days and echoes it in a chosen format. If $date is null, it will just echo an empty string - ''.
Edit: The above is just an one-liner example, a good practice would be getting it into a function.

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

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

PHP date() - error in finding date in between

I'm using the following code to see if a date falls between 2 other dates.
public function dateCompare($date1, $date2)
{
$interimDate = date('d/m/Y');
$StartDate = DateTime::createFromFormat('d/m/Y', $date1);
$EndDate = DateTime::createFromFormat('d/m/Y', $date2);
if ($interimDate > $StartDate && $interimDate < $EndDate)
{
echo 'Falls during given period';
}
else {
echo 'Does not fall during given period';
}
The two dates passed as follows
dateCompare('01/08/14', '30/12/14');
For some reason I continually get the message that todays date does not fall between the given period. I have checked the servers datetime and it is correct. Is anyone able to point out what exactly is causing the error?
You have a 2 letter years, so it should be lower case y for your format: d/m/y.
Also, make $interimDate equal to a new DateTime() object so you can compare properly.

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