PHP - Is a date in the past - php

I'm trying to compare if a date is today, or in the past. As far as i can tell i should be able to do date1 <= today but it shows as true even if the date is in the future
I'm getting the date from the database and adding 30 days to it using
echo "End Date: " . $rowTicket['endDate'] . "<br/>";
$disableDate = ($rowTicket['endDate'] != '0000-00-00') ? date('d-m-Y', strtotime('+30 days', strtotime($rowTicket['endDate']))) : '';
And then doing the check using
echo "Is " . $disableDate . " before today's date? (" . date("d-m-Y") . ")";
if($disableDate <= date("d-m-Y")) {
//$colourTR = $red;
echo " - Yes<br/><br/>";
} else {
echo " - No<br/><br/>";
}
The output i get from the echo's is
End Date: 2021-09-01
Is 01-10-2021 before today's date? (26-10-2021) - Yes
End Date: 2021-10-15
Is 14-11-2021 before today's date? (26-10-2021) - Yes

Because you compare strings, while should compare timestamps
echo "End Date: " . $rowTicket['endDate'] . "<br/>";
$disableDate = $rowTicket['endDate'] != '0000-00-00'
? strtotime('+30 days', strtotime($rowTicket['endDate']))
: '';
$today = strtotime('today midnight');
echo "Is {$disableDate} before today's date? (" . date("d-m-Y", $today) . ")";
if($disableDate <= $today) {
//$colourTR = $red;
echo " - Yes<br/><br/>";
} else {
echo " - No<br/><br/>";
}

You are formatting your dates as strings. PHP has no way of knowing that the string '26-10-2021' should be "less than" the string '14-11-2021'.
If you format them year-first ('Y-m-d'), it will work, but better to compare the integer timestamps (output of strtotime), or DateTimeImmutable objects.

Related

PHP check if date is expired

i have an Array with this string value.
[VALIDUNTIL] => 28.08.23
Now i need to compare it with the todays date and check if the VALIDUNTIL date is in the same month and year as the today´s date
i looked for a while now but i cant find any solution.
while ($row = oci_fetch_assoc($dbResult))
{
$data[] = $row;
}
foreach($data as $ar) {
if ($ar['VALIDUNTIL'] && $ar['VALIDUNTIL'] != null) {
if(strtotime($ar['VALIDUNTIL']) >= strtotime($date)) {
}
}
When i try to do it with timestamps it cant read the VALIDUNTIL date and gives me the 1970 timestamp
strtotime seems not to work too.
tnx 4 help.
while ($row = oci_fetch_assoc($dbResult))
{
if(!empty($row['VALIDUNTIL']) && !is_null($row['VALIDUNTIL'])){
$valid_date = date('d-m-Y', strtotime($row['VALIDUNTIL']));
$current_date = date('d-m-Y');
if($valid_date >= $current_date ) {
echo "True";
}
}
}
Here are the PHP string conversions for time ref. https://www.w3schools.com/php/php_ref_date.asp
echo(strtotime("now") . "<br>");
echo(strtotime("3 October 2005") . "<br>");
echo(strtotime("+5 hours") . "<br>");
echo(strtotime("+1 week") . "<br>");
echo(strtotime("+1 week 3 days 7 hours 5 seconds") . "<br>");
echo(strtotime("next Monday") . "");
echo(strtotime("last Sunday"));
You'd need to have both dates in the same format. The above is from : https://www.w3schools.com/php/func_date_strtotime.asp#:~:text=The%20strtotime()%20function%20parses,are%20mapped%20to%201970%2D2000.
if you echo (strtotime($ar['VALIDUNTIL']) and strtotime($date)) back to the screen then you can visually compare and check to see the format which you are using is the same for both dates and adjust accordingly.

I want to set the winning day of the event as a weekday, but is it possible to resolve the error?

// holiday array
$holy = [
'2020-12-23',
'2020-12-24',
'2020-12-25',
'2020-12-28',
'2020-12-29',
];
$inputDate = '2020-12-23'; // input
$outputDate = get_date($inputDate);
echo "Winning Day: " . $outputDate . "<br />";
echo "<br />";
function get_date($chkDate)
{
global $holy;
$chkDateYoil = date("w", strtotime($chkDate)); // sat(6), sun(0)
if ($chkDateYoil == 6) {
// Saturday when + 2
$timestamp = strtotime($chkDate . " +2 days");
$chkDate = date("Y-m-d", $timestamp);
} else if ($chkDateYoil == 0) {
// Sunday when + 1
$timestamp = strtotime($chkDate . " +1 days");
$chkDate = date("Y-m-d", $timestamp);
}
// If it's a weekday, compare it array
foreach ($holy as $key => $holyday) {
if ($chkDate == $holyday) {
// holiday when + 1
$day_plus = 8 - $chkDateYoil;
$timestamp = strtotime($chkDate." +".$day_plus." days");
$chkDate = date("Y-m-d", $timestamp);
}
}
return $chkDate;
}
Hello, let me ask a question.
The following codes are:
Is the input value weekend?
Or are they included in the array?
in accordance with the judgment
Weekday extraction code.
But there is an error.
in my estimation
December 30th is supposed to come out.
By the way, January 2, 2021 is the result.
Why is that?
sorry
i don't write english very well
Thank you for reading.
The problem is in this line: $day_plus = 8 - $chkDateYoil;, which is calculating the date of the next Monday the first time it's executed.
You're then looping through the rest of the $holy array, and updating $chkDate if necessary, but you're not recalculating the value of $chkDateYoil, so the output depends on the day of the week you run this. Today (23rd December) it stops on 2nd January
Your code can be simplified by just incrementing the date by 1 day and performing the checks again, continuing until you get a result. I've also used the PHP function in_array() to simplify the search of the $holy array, and incorporated it into the same test as Saturday and Sunday.
// holiday array
$holy = [
'2020-12-23',
'2020-12-24',
'2020-12-25',
'2020-12-28',
'2020-12-29',
];
$inputDate = '2020-12-23'; // input
$outputDate = get_date($inputDate);
echo "Winning Day: " . $outputDate . "<br />";
echo "<br />";
function get_date($chkDate)
{
global $holy;
do {
$chkDateYoil = date("w", strtotime($chkDate)); // sat(6), sun(0)
if (($chkDateYoil == 0) || ($chkDateYoil == 6) || (in_array($chkDate, $holy))) {
$timestamp = strtotime($chkDate . " +1 days");
$chkDate = date("Y-m-d", $timestamp);
} else {
return $chkDate;
}
} while (true);
}

PHP if date is older than X days

I have some problems with dates. I need make if like --->
if your activity is less than 1 day do somethink
else if your activity is more than 1 day and less than 3 do moething else
else if your activity is more than 3 do moething else
I need this in PHP. My actual code is:
if (strtotime(strtotime($last_log)) < strtotime('-1 day') ) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive less than 1 day") . ",";
} else if (strtotime($last_log) > strtotime('-1 day') && strtotime($last_log) < strtotime('-3 day')) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive more than 1 day and less than 3 days") . ",";
} else if (strtotime($last_log) > strtotime('-3 day')) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive more than 3") . ",";
}
I think I really don't understand date calculations.
Date_diff is much easier in this case:
$datetime1 = date_create(); // now
$datetime2 = date_create($last_log);
$interval = date_diff($datetime1, $datetime2);
$days = $interval->format('%d'); // the time between your last login and now in days
see: http://php.net/manual/en/function.date-diff.php
Or in your way:
if(strtotime($last_log) < strtotime('-1 day')){
// it's been longer than one day
}
If you want to do it with strtotime, do it like this:
date_default_timezone_set('SOMETHING FOR YOU');
$last_log = '-0.5 day';
$last_log_time = strtotime($last_log);
$minus1day_time = strtotime('-1 day');
$minus3day_time = strtotime('-3 day');
echo $last_log_time . "<br>";
echo $minus1day_time . "<br>";
echo $minus3day_time . "<br>";
if ($last_log_time < $minus3day_time)
{
echo "inactive more than 3";
}
elseif ( ($last_log_time <= $minus1day_time) && ($last_log_time >= $minus3day_time) )
{
echo "inactive more than 1 day and less than 3 days";
}
elseif ($last_log_time > $minus1day_time)
{
echo "inactive less than 1";
}
Couple things I changed from your code:
remove the strtotime(strtotime()). Do not do it twice!
For your second if, I added parentheses to ensure correct evaluation of conditions.
I reversed the order of your if. First check if it is very old (so < -3). Then check if it is between -3 and -1. Then check between -1 and now.
Added <= and >=. The = cases were missing from your code. So if the last_log was == -1, it was not processed ever.
I replace "else if" by "elseif".
I used variables because recalculating strtotime all over is wasteful. And it makes the code less readable IMHO.
Then apply the json_encode comment.
To explain why the logic was reversed:
the last login of a user will always be before now.
lets say that the user's last_login is 5 days ago. strtotime($last_login) will be smaller than strtotime('-1 days'), so the if will be true. But that is not what the OP wants! He wants here the case where the last login is older than 3 days.
Remember that we are comparing numbers in the past, so the smaller, the older.
$dateLog = new DateTime($last_log); // format if needed
$tomorrow = new DateTime("tomorrow");
$yesterday = new DateTime("yesterday");
$threeDaysAgo = new DateTime("-3 days");
if ($dateLog < $yesterday) {
// Do what you want
} else if ($dateLog > $yesterday && $dateLog < $threeDaysAgo) {
// Do another thing
} else if ($dateLog > $threeDaysAgo) {
// ...
}
The doc is here : http://php.net/manual/en/datetime.diff.php

Having trouble comparing a range of dates entered in a form with records in a mySQL database

I have a table called schedule and a column called Date where the column type is date. In that column I have a range of dates, which is currently from 2012-11-01 to 2012-11-30. I have a small form where the user can enter a range of dates (input names from and to) and I want to be able to compare the range of dates with the dates currently in the database.
This is what I have:
////////////////////////////////////////////////////////
//////First set the date range that we want to use//////
////////////////////////////////////////////////////////
if(isset($_POST['from']) && ($_POST['from'] != NULL))
{
$startDate = $_POST['from'];
}
else
{
//Default date is Today
$startDate = date("Y-m-d");
}
if(isset($_POST['to']) && ($_POST['to'] != NULL))
{
$endDate = $_POST['to'];
}
else
{
//Default day is one month from today
$endDate = date("Y-m-d", strtotime("+1 month"));
}
//////////////////////////////////////////////////////////////////////////////////////
//////Next calculate the total amount of days selected above to use as a limiter//////
//////////////////////////////////////////////////////////////////////////////////////
$dayStart = strtotime($startDate);
$dayEnd = strtotime($endDate);
$total_days = abs($dayEnd - $dayStart) / 86400 +1;
echo "Start Date: " . $startDate . "<br>End Date: " . $endDate . "<br>";
echo "Day Start: " . $dayStart . "<br>Day End: " . $dayEnd . "<br>";
echo "Total Days: " . $total_days . "<br>";
////////////////////////////////////////////////////////////////////////////////////
//////Then we're going to see if the dates selected are in the schedule table//////
////////////////////////////////////////////////////////////////////////////////////
//Select all of the dates currently in the schedule table between the range selected.
$sql = ("SELECT Date FROM schedule WHERE Date BETWEEN '$startDate' AND '$endDate' LIMIT $total_days");
//Run a check on the query to make sure it worked. If it failed then print the error.
if(!$result_date_query = $mysqli->query($sql))
{
die('There was an error getting the dates from the schedule table [' . $mysqli->error . ']');
}
//Set the dates to an array for future use.
// $current_dates = $result_date_query->fetch_assoc();
//Loop through the results while a result is being returned.
while($row = $result_date_query->fetch_assoc())
{
echo "Row: " . $row['Date'] . "<br>";
echo "Start day: " . date('Y-m-d', $dayStart) . "<br>";
//Set this loop to add 1 day to the Start Date until it reaches the End Date
for($i = $dayStart; $i <= $dayEnd; $i = strtotime('+1 day', $i))
{
$date = date('Y-m-d',$i);
echo "Loop Start day: " . date('Y-m-d', $dayStart) . "<br>";
//Run a check to see if any of the dates selected are in the schedule table.
if($row['Date'] != $date)
{
echo "Current Date: " . $row['Date'] . "<br>";
echo "Date: " . $date . "<br>";
echo "It appears as though you've selected some dates that are not in the schedule database.<br>Please correct the issue and try again.";
return;
}
}
}
//Free the result so something else can use it.
$result_date_query->free();
As you can see I've added in some echo statements so I can see what is being produced. From what I can see it looks like my $row['Date'] is not incrementing and staying at the same date. I originally had it set to a variable (currently commented out) but I thought that could be causing problems.
I have created the table with dates ranging from 2012-11-01 to 2012-11-15 for testing and entered all of this php code onto phpfiddle.org but I can't get the username provided to connect.
Here is the link: PHP Fiddle
I'll be reading through the documentation to try and figure out the user connection problem in the meantime, I would really appreciate any direction or advice you can give me.

Schedule Post - Displaying Some Content only for Some time or any time in future or Repitative

I am trying to display some content only for some time or some days
I have start time, start date, end time and end date in database so that when the data is fetched from database this time and dates should be checked and display the content accordingly
My code that i have tried
$startDateTime = strtotime($result['StartDate']." ".$result['StartTime']);
$endDateTime = strtotime($result['EndDate']." ".$result['EndTime']);
$now = time();
echo "START : ".$startDateTime;
echo "<br/>END : ".$endDateTime;
echo "<br/>CURRENT : ".$now;
if($now >= $startDateTime && $now <= $endDateTime){
echo $result['content'];
}
But its not working its displaying the content every time
Please Help Me
Thanks in advance
output a list of your $result['StartDate']." ".$result['StartTime'] I think you'll find that it might be leaving off leading 0's or something which would give it trouble casting it as a time.
Rather than using the time() function - try creating '$now' as strtotime("now").
Also, as a debugging step, it probably would have helped you to echo the comparisons to see if they evaluated the way that you expected.
Actually - I just tried your code exactly as it was...Except that I had hard coded values for the starting and ending dates and times. And it worked, so switching to use strtotime("now") will probably not make a difference.
What are the values that were printed out? You didn't tell us.
So VoronoiPotato is probably right...The values you are storing for StartDate/StartTime and EndDate/EndTime must have something wrong with them.
What is the output of your program if you change it like this (to add more debugging):
$startDateTime = $result['StartDate'] . " " . $result['StartTime'];
$endDateTime = $result['EndDate'] . " " . $result['EndTime'];
$now = time();
echo "START : " . $startDateTime."<br />\n";
echo "END : " . $endDateTime . "<br />\n";
$startDateTime = strtotime($startDateTime);
$endDateTime = strtotime($endDateTime);
echo "Start as time: " . $startDateTime . "<br />\n";
echo "End as time: " . $endDateTime . "<br />\n";
echo "CURRENT : " . $now . "\n";
if (($now >= $startDateTime) && ($now <= $endDateTime)) {
echo $result['content'];
}

Categories