Conditional DateDiff - php

I had visited some of the post retrieving the date difference between 2 dates in SO but it doesn't gave me the answer I was seeking. Same for reading the documentation, I had problem understanding how it works.
I have tried coding it but it doesn't behave like what I was expecting. Here is my code:
<?php
$currentDate = new DateTime();
$createDateJoin = date_create($getDate['date_joined']);
$dateJoin = date_format($createDateJoin, "Y-m-d");
$yearDifference = $currentDate->diff($createDateJoin);
if ($yearDifference->d < 31 && $yearDifference->m = 0 && $yearDifference->y == 0) {
echo $yearDifference->d . " days";
} else if ($yearDifference->m > 3) {
echo $yearDifference->m . " month";
} else if ($yearDifference->y > 1) {
echo $yearDifference->y . " years";
} else {
echo "Not yet assigned";
}
?>
As you can see from my code above, I am trying to do a print when after calculating the difference between the 2 dates, it meets the condition of $yearDifference->.The behavior from the program that I have experienced does not print out the things I want accordingly (E.g Staff working more than 1 year will print out how many years they have work, months for those who just came in and new staff less than a month will print out days).
I would like to know how does ->d/m/y works and how can I actually make use of the d,m and y to draw out the specific date correctly. And I also noticed that when I treat $yearDifference as a String or int, it comes out different result for the conditions. So what should I treat the type to be to manipulate it more easily? Greatly appreciate the help.

You can use this code to get the date different method diff() object returns more values to check you can print_r your object that will print all data member that are returned via diff() method
<?php
echo get_date_diff(strtotime('1990-10-12'),strtotime('2015-10-14'));
function get_date_diff($date,$dateEnd) {
$dStart = new DateTime(date("Y-m-d", $date));
$dEnd = new DateTime(date("Y-m-d", $dateEnd));
$dDiff = $dStart->diff($dEnd);
return($dDiff->y.' years <br>'.$dDiff->m.' months <br>'.$dDiff->d. ' days');
}
?>

Related

PHP - Compare multiple date-time's with +60sec

Obviously I'm missing something, but can't figure out how to compare strings which are date&time but both got in different ways.
Code:
$mod_datetime = get_the_modified_date() .' '.get_the_modified_time();
$curr_datetime = date('Y-m-d H:i');
$plus_datetime = strtotime($mod_datetime) <= 0*0*0*60;
date_default_timezone_set('Europe/Warsaw');
if( ($curr_datetime < strtotime($mod_datetime)) > $plus_datetime){
echo 'True';
} elseif ( 0*0*0*60 < (time() < strtotime($mod_datetime)) ) {
echo 'Recently false';
} else {
echo 'False at all';
}
}
In wordpress to get post last modification date and time - has to use $mod_datetime which gives me return like: 2021-05-09 15:21. String $curr_datetime returns me in same format, like: 2021-05-09 15:21 (it's all good with getting last modification date and current date.
But trouble is I'm getting wrong result in echo and obviously my if statement is in wrong way written. How to compare like:
if post has been edited 60 or less seconds ago - return true, otherwise - return false and goodbye, have a nice day.
Any thoughts appreciated.

Row highlighting based on due date using php

I'm relatively new to PHP, I've learned procedural PHP and I'm playing around with an app.
I've Looked around the site and found a few samples on date formatting and highlighting using PHP, HTML and CSS.
With the help found here and the PHP manual, I've put together some code to highlight 2 different rows among many others provided by a database that follow this criteria:
Anything due in 1 day (today, yesterday, last week, etc.) should color the table row red.
Anything 3 days out (between 1 day and 3 days in the future) should color the table row yellow.
Anything else should utilize the bootstrap "table-striped" styling.
Here is the code I've put together
//Today + 1 day
$oneDay = date('m/d/Y', strtotime("+1 day"));
//Today + 3 days
$threeDays = date('m/d/Y', strtotime("+3 days"));
//Database entry for comparison
$due = date_create($record['projected_delivery']);
$dueOneDay = date_create($oneDay);
$dueThreeDays = date_create($threeDays);
//Get the difference between the 2 dates
$diffOne = date_diff($due, $dueOneDay);
$diffThree = date_diff($due, $dueThreeDays);
if ($diffThree->format('%d') < 3) {
$highlight_css = " warning";
}elseif ($diffOne->format('%d') <= 1){
$highlight_css = " danger";
}else {
$highlight_css = "";
}
I then add the $highlight_css to the HTML.
So far some of the functionality is working. Proper highlighting is not added for:
Dates older than 1 day (i.e. yesterday, last week)
How can this functionality be achieved?
I would use this instead:
<?php
$dueDates =["06/05/2017","06/06/2017","06/07/2017","06/08/2017","06/09/2017","06/10/2017","06/11/2017","06/12/2017"];
$table = "<table class='table table-bordered'><thead><tr><th>Date</th></tr></thead><tbody>";
$today = date_create(date('m/d/Y')); // example: 06/07/2017
foreach ($dueDates as $dueStr) {
$due = date_create($dueStr);
$diff = date_diff($today, $due)->format("%r%a");
$highlight_css = "";
if ($diff > 1 && $diff <= 3) {
$highlight_css = " warning";
} elseif ($diff == 1) {
$highlight_css = " danger";
}
$table .= "<tr class='$highlight_css'><td>$dueStr</td></tr>";
}
$table .= "</tbody></table>";
?>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" >
<?php
echo $table;
$diffThree->format('%d')
will return a string instead of an integer. In order to compare it correctly with other numbers (3 and 1 in your case) you need to convert it to an int:
(int) $diffThree->format('%d')
and
(int) $diffOne->format('%d')
The issue
A DateInterval (the return value of date_diff()) has the number of days (actually stored in a property d, which could be used instead of getting a string with format()), which should always be a positive number. And for dates before today's date, the first date diff (i.e. $diffOne) will be 2+ days and the second date diff (i.e. $diffThreeDays) will be 4+ (see this playground example with debugging output above the table) so days before today's date will never be associated with either 'warning' or 'danger' according to the given logic.
A Solution
One approach (perhaps simpler) to comparing the dates is to use DateTime comparison
Note:
As of PHP 5.2.2, DateTime objects can be compared using comparison operators.1
So compare the DateTime variables (i.e. $due with $dueOneDay and $dueThreeDays) instead of the date differences.
In the logic below, you will notice that the order of the comparisons has been reversed, so the check for one day difference comes before the check for three days difference, in order to avoid the danger case never happening.
if ($due < $dueOneDay){
$highlight_css = " danger";
}else if ($due <= $dueThreeDays) {
$highlight_css = " warning";
}else {
$highlight_css = "";
}
With this approach, there is no need for the date_diff variables (i.e. $diffOne, $diffThree).
See a demonstration of this in this playground example.
1http://php.net/manual/en/datetime.diff.php#example-2524

Why I can't successfully subtract two datetime values in php?

I have the following code:
echo "first row " . $firstRow["begin_date"];
echo " super beg " . $superbegintime;
echo " duration " . $duration;
if(($firstRow["begin_date"] - $superbegintime) >= $duration)
{
echo "it works!";
}
$firstRow["begin_date"] is a DATETIME type field taken from database
$superbegintime is created as follows:
$date = new DateTime();
$superbegintime= $date->add(DateInterval::createFromDateString('10 minutes'))->format('Y-m-d H:i:s');
and $duration is a field $duration = 15; that should represent number of seconds.
I cannot enter the if statement and print the it works! message, what am I doing wrong here?
You are comparing and doing math with strings which can be problematic and not get you the right results especially when you compare them to integers (and don't specify what that number actually means). DateTime objects allow you to do the math and then compare the difference with the duration. The difference and the duration are both DateInterval objects which are comparable.
$beginDate = new DateTime($firstRow["begin_date"]);
$superbegintime = new DateTime($superbegintime);
$duration = DateInterval::createFromDateString('15 seconds');
$diff = $beginDate->diff($superbegintime);
if($diff >= $duration)
{
echo "it works!";
}
Demo

Php custom date format and comparison

In my database I have one table in which I keep registered users.
One column is Date of register and I keep this value in my own string format.
For example "[2013-11-30] [19:42:46]"
Then I want to make a check.
If user is 30 days old or more.
The sure thing is that the above code is wrong.
The problem is that if one user registers at 29/01/2015
will not been showing in 30 last days if the current day is 02/02/2015!
//Datetime
$today = date_parse_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_parse_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if (
(($store[year] >= $today[year]) && ($store[month] >= $today[month]))
)
{ $date_last = "<font color='green'>".$row["LastSeen"]."</font>"; }
else
{ $date_last = "<font color='red'>".$row["LastSeen"]."</font>"; }
Use date_create_from_format instead of date_parse_from_format. Then you can simply compare the resulting values:
$today = date_create_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_create_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if ($store < $today) {
// ...
}
else {
// ...
}

If Statement with date

I am doing an assignment for school, and I get bonus marks if I add a discount on a certain day. I have an actively updating time, using the date function(is it a function?) but I don't know how I would go about making an if statement for this.
Here is my code:
<?php
$t = time();
echo "Date of Purchase: " . (date("Y-m-d", $t));
if(date == "20140224") {
echo $b;
echo "It works!";
}
?>
Obviously I only provided relevant code. Any help is appreciated!
Use DateTime() as DateTime objects are comparable:
$today = new DateTime();
$discountDate = new DateTime('2014-02-24');
if ($today == $discountDate) {
// today is discount day!
}
Tip: No need to use time() to pass a second parameter to date(). date() always assumes "now" when no second parameter is passed
This is untested, but the idea is that you have a function with parameters.
function getPrice($price, $search_date, $happyDays=5) {
if(date('w', strtotime($search_date)) == $happyDays) {
return $price * 0.8; // 20% discount
} else {
return $price; // full price
}
}
Call it like so:
echo "Sum: " . getPrice(100, $_SESSION['purchase_date']);
Ps. I use a session date value, since I think the customer should get the discount if he/she places the order just before midnight :-) (as long as the session is still alive).

Categories