Compare difference between two dates PHP - php

I am trying to compare to date to figure out how much time is between them, which I know how to do, date_diff(), but I want to then compare the time between the dates and if it is greater than 7 days do something and if not do something else. I think it sounds easy and I know there are probably fairly simple solutions to do so but I am just not a fan of dates and comparisons. Here is a snippet of what I got so far as it is just one case of a switch statement so the rest are basically identical.
$array = array();
$today = date("Y-m-d"); // get today's date
foreach($arrayOfObjs as $obj){
if ($obj->get("renewalDate") >= $today){
array_push($array, $obj->get("renewalDate"));
}else{
switch($obj->get("recurrencePeriod")){
case 1:
/*
* All cases follow same structure
* Build the date in format Y-m-d from renewalDate out of the obj.
* Loop through the date while it's less than today.
* After date is greater than today return date add to array
*/
$date = DateTime::createFromFormat("Y-m-d", $obj->get('renewalDate'));
while($date <= $today){
$date->add(new DateInterval('P7D'));
}
$diff = date_diff($today, $date);
if($diff->format('%a') <= 7){
$obj->renewalDate($date);
array_push($array, $obj);
}
break;
Basically, my database stores dates and those dates could be passed but it could be a reoccurring event. To calculate the next time that event would happen I check if the data in the database is before today's date and if it is then I continue to add the incremental amount (in this case 7 for a weekly reoccurring event) and compare the dates again. After the date that is incremented passes today's date I want to find out if it is within 7 days and if so add it to an array to get returned. I know... since I'm adding 7and it's within 7 days the first reoccurring event will always be within 7 days but that is not the case for monthly events or anything greater.
All cases are broken so I only included this one for simplicity. I can get date_Diff to return something like 7 or 12 or whatever the number may be but how can I check if that number is within the 7 days I want?
Thanks, I will include more information if needed to clarify any misunderstandings.

I'm not entirely sure what you are trying to do, but how about the following if you are just projecting dates forward and backwards and want to know if they are 7 days or more either way:
$today = date("Y-m-d");
$todaytime = strtotime($today);
$testdate = "2017-06-31";
$testtime = strtotime($testdate);
$back7days = strtotime("-7 days",$todaytime);
if($testtime < $back7days)
echo "X"; // do somthing if testdate was more than 7 days ago
$fwd7days = strtotime("+7 days", $todaytime);
if($testtime > $fwd7days)
echo "Y"; // do somthing if testdate is more than 7 days in future
Just make sure that you use less-than or less-than-and-equals comparators etc to handle the boundary conditions you need.

Related

Is there a function to calculate weekdays from today PHP

I'm writing a code which need to calculate the number of weekdays from a date to today.
I just have today's date and with that i want to pass a number to the function so it can return me back the number of weekdays since x days.
e.g :
function getWorkingDays($number){
// code...
return $value;
}
// if we are monday
getWorkingDays(2) // return Thursday's date
I got this problem since two days now and i'm getting very boring, hope someone got a solution.
This is very easy to do with the DateTime object:
$date = date_create('2020-01-06'); //a Monday
$numberWeekdays = 2;
$date->modify('-'.$numberWeekdays.' weekdays');
echo $date->format('l Y-m-d');
//Thursday 2020-01-02
If you need Today as the basis , you can also use date_create('Today').

In php check if an item is between a given date range

I'm suck on the logic for this, my goal is to execute if an item is with in a given date range.
I get yesterday's date and the date from 8 days ago with Carbon like so:
$dt = \Carbon\Carbon::yesterday();
$dtB = \Carbon\Carbon::yesterday()->subDays(8);
$today = $dt->toDateString();
$todayBack = $dtB->toDateString();
I then need to execute this if statement to find if the item in the database fits with in these time frames.
if($orderSet->item_clicked == 'printing' && $orderSet->completed_date == $today) {
// run some stuff here
}
Currently I can execute if it's today but I would like do in between these two days. In example. 09-20-19 - 10-09-19 in between these two dates. Just as an example.
Carbon has a between() method. Use the original carbonized dates instead of the date strings.
$dtCompleted = \Carbon\Carbon::parse($orderSet->completed_date);
if (if($orderSet->item_clicked == 'printing' && $dtCompleted->between($dtB, $dt)) {
// run some stuff
}
See the documentation of Comparison

Generating a date based on a weekinterval, a day, and an existing date

I have a database with different workdates, and I have to make a calculation that generates more dates based on a weekinterval (stored in the database) and the (in the database stored) days on which the workdays occur.
What my code does now is the following:
Read the first two workdates -> Calculate the weeks inbetween and save the week interval
Read all the workdates -> fill in the days on which a workdate occurs and save it in a contract.
Generate workdates for the next year, based on the week interval.
The point is: for each week with a week interval of 1, more days of the week should be saved as a workdate. I've used this code to do this, but it doesn't work.
// Get the last workdate's actdate.
$workdate_date = $linked_workdate['Workdate']['workdate_actdate'];
// Calculate the new workdate's date
$date = date("Y-m-d", strtotime($workdate_date . "+" . $interval . " week"));
// If 'Monday' is filled in for this contract, calculate on which day the
// Monday after the last interval is. Same for each day, obviously.
// The days are boolean.
if ($contract['Contract']['contract_maandag'] = 1){
$date = date("Y-m-d", strtotime($date, "next Monday"));
}
if ($contract['Contract']['contract_dinsdag'] = 1){
$date = date("Y-m-d", strtotime($date, "next Tuesday"));
}
// After this, save $date in the database, but that works.
Here is the error that i get:
strtotime() expects parameter 2 to be long, string given
I'm quite stuck right now, so help is appreciated!
if ($contract['Contract']['contract_maandag'] = 1){
if ($contract['Contract']['contract_dinsdag'] = 1){
This won't work. You're doing an assignment (=), so it's always true. But you want a comparison (===). It is recommended to do always (except required otherwise) to use strict (===) comparison.
Well, the = doesn't seem to be the problem, since the error is about the part that's after the comparison. Try
strtotime("$date next Monday");

How to determine if a date is more than three months past current date

I am getting a date back from a mysql query in the format YYYY-MM-DD.
I need to determine if that is more than three months in the past from the current month.
I currently have this code:
$passwordResetDate = $row['passwordReset'];
$today = date('Y-m-d');
$splitCurrentDate = explode('-',$today);
$currentMonth = $splitCurrentDate[1];
$splitResetDate = explode('-', $passwordResetDate);
$resetMonth = $splitResetDate[1];
$diferenceInMonths = $splitCurrentDate[1] - $splitResetDate[1];
if ($diferenceInMonths > 3) {
$log->lwrite('Need to reset password');
}
The problem with this is that, if the current month is in January, for instance, giving a month value of 01, and $resetMonth is November, giving a month value of 11, then $differenceInMonths will be -10, which won't pass the if() statement.
How do I fix this to allow for months in the previous year(s)?
Or is there a better way to do this entire routine?
Use strtotime(), like so:
$today = time(); //todays date
$twoMonthsLater = strtotime("+3 months", $today); //3 months later
Now, you can easily compare them and determine.
I’d use PHP’s built-in DateTime and DateInterval classes for this.
<?php
// create a DateTime representation of your start date
// where $date is date in database
$resetDate = new DateTime($date);
// create a DateIntveral representation of 3 months
$passwordExpiry = new DateInterval('3M');
// add DateInterval to DateTime
$resetDate->add($passwordExpiry);
// compare $resetDate to today’s date
$difference = $resetDate->diff(new DateTime());
if ($difference->m > 3) {
// date is more than three months apart
}
I would do the date comparison in your SQL expression.
Otherwise, PHP has a host of functions that allow easy manipulation of date strings:
PHP: Date/Time Functions - Manual

PHP DateInterval: Diff between same date in two different months is not one month

I am developing a subscription service where the user pays per month.
I am having two dates
1: 2012-12-05 ($today)
2: 2013-01-05 ($end_date)
For me, that is one month. But for PHP, that is only 30 days.
Here is some code (you can see the values of the dates mapped above)
$end_date_for_new_agents = clone $end_date;
$end_date_for_new_agents = $end_date_for_new_agents->add(new DateInterval("P1D"));
$agent_period_months_obj = $today->diff($end_date_for_new_agents);
echo $agent_period_months_obj->format("%y-%m-%d")
This echos 0-0-30
Why is that and how can I make PHP calculate the difference between the same dates in different months as whole months?
You should condider also the time, or the day can be not complete.
For example:
date_default_timezone_set("Europe/Rome");
$end='2013-01-05';
$intervalo = date_diff(date_create(), date_create($end));
echo $intervalo->format("Years:%Y,Months:%M,Days:%d,Hours:%H,Minutes:%i,Seconds:%s");
give as result:
Years:00,Months:00,Days:30,Hours:05,Minutes:59,Seconds:53
The following code
date_default_timezone_set("Europe/Rome");
$start='2012-12-05';
$end='2013-01-05';
$intervalo = date_diff(date_create($start), date_create($end));
echo $intervalo->format("Years:%Y,Months:%M,Days:%d,Hours:%H,Minutes:%i,Seconds:%s");
give the result:
Years:00,Months:01,Days:0,Hours:00,Minutes:0,Seconds:0
Check if value of$today has also the time, if so you should extract only the date and forget the time

Categories