Date difference in PHP code does not execute - php

I have a code in PHP 5.5.11 where I am trying to do the following:
Get today's date in a variable --> $today
Calculate the end of month from a date in a form --> $st_dt_eom
if difference between these 2 dates is more than 5 days then execute a code. The code in the if condition below does not execute.
$today= date();
if($_POST['Submit']=='SAVE')
{
$st_dt=YYYYMMDD($_POST['st_dt'],"-");
$st_dt_eom= datetime::createfromformat('YYYYMMDD',$st_dt);;
$st_dt_eom->modify('last day of this month');
$diff = $today->diff($st_dt_eom);
$diffDays= intval($diff->format("%d")); //to get integer number of days
if($diffDays>5){
redirect("index.php");
}
}

An example:
// 2022-12-19
$today = date('Y-m-d');
// $_POST['st_dt']
$st_dt = '2022-12-31';
function dateDiffDays($today, $st_dt)
{
$today_obj= DateTime::createfromformat('Y-m-d', $today);
$st_dt_eom= DateTime::createfromformat('Y-m-d', $st_dt);
$diff = $today_obj->diff($st_dt_eom);
return $diff->days;
}
// int(12)
$res = dateDiffDays($today, $st_dt);
use var_dump to locate your bug.

A few suggestions to improve your code and produce something workable:
<?php
// Instead of using date(), use a DateTime() then you're comparing two DateTimes later on
$today = new DateTime();
// I'm assuming that your YYYYMMDD function removes "-" from the $_POST['st_dt']
// to provide a date in the format YYYYMMDD (or Ymd in PHP).
// Unfortunately, DateTime doesn't understand that format.
// So I'd change this for keeping Y-m-d (YYYY-MM-DD).
// Or modify your code to return that format!
$st_dt = $_POST['st_dt'];
// Watch out for your cAsE when using PHP functions!
$st_dt_eom = DateTime::createFromFormat('Y-m-d',$st_dt);
$st_dt_eom->modify('last day of this month');
$diff = $today->diff($st_dt_eom);
$diffDays= intval($diff->format("%d"));
if($diffDays > 5){
redirect("index.php");
}

Related

How to retrieve the number of days from a PHP date interval?

I am trying to retrieve the number of days for a PHP interval. When I run the following piece of code on http://sandbox.onlinephpfunctions.com/:
$duration = new \DateInterval('P1Y');
echo $duration->format('%a');
echo "Done";
I get:
(unknown)Done
What am I doing wrong?
The '%a' will return the number of days only when you take a time difference otherwise it will return unknown.
You can use '%d' to get the days but it will also return 0 in the case of new \DateInterval('P1Y') as it does not convert years to days.
One easy way to get the number of days is to create a DateTime at zero time, add the interval to it, and then get the resulting timestamp:
<?php
$duration = new \DateInterval('P1Y');
$intervalInSeconds = (new DateTime())->setTimeStamp(0)->add($duration)->getTimeStamp();
$intervalInDays = $intervalInSeconds/86400;
echo $intervalInDays;
echo " Done";
The problem is here:
$duration->format('%a');
As the manual says, "Total number of days as a result of a DateTime::diff() or (unknown) otherwise".
You need a valid dateInterval object returned by DateTime's diff() method to make the "a" parameter work with DateInterval::format() function:
$now = new DateTime(date('Y-m-d H:i:s'));
$duration = (new DateTime("+1 year"))->diff($now);
echo $duration->format('%a');
Looks like if the DateInterval object is not created by DateTime::diff(), it won't work.
Hope it helps.
You have to create the interval with real dates:
<?php
$interval = date_diff(new DateTime, new DateTime('+1 year'));
echo $interval->format('%a'), PHP_EOL; // 365
if you want something aware of the year or month context, use this, february will return 28 days, leap years will have their additional day
function interval2days($day, $interval) {
$date = clone $day;
$start = $date->getTimeStamp();
$end = $date->add($interval)->getTimeStamp();
return ($end-$start)/86400;
}

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

How to get difference between two day in php

I have on function which passing some parameter the like
everyWeekOn("Mon",11,19,00)
I want to compute the difference between the current day (e.g. 'Fri')
and passed parameter day i.e. Mon.
The output should be:
The difference between Mon and Fri is 3
I tried it like this
$_dt = new DateTime();
error_log('$_dt date'. $_dt->format('d'));
error_log('$_dt year'. $_dt->format('Y'));
error_log('$_dt month'. $_dt->format('m'));
But know I don't know what to do next to get the difference between the two days.
Note that this question is different from How to calculate the difference between two dates using PHP? because I only have a day and not a complete date.
Just implement DateTime class in conjunction with ->diff method:
function everyWeekOn($day) {
$today = new DateTime;
$next = DateTime::createFromFormat('D', $day);
$diff = $next->diff($today);
return "The difference between {$next->format('l')} and {$today->format('l')} is {$diff->days}";
}
echo everyWeekOn('Mon');
$date = new DateTime('2015-01-01 12:00:00');
$difference = $date->diff(new DateTime());
echo $difference->days.' days <br>';
You can find no. of days in two days by using this code
<?php
$today = time();
$chkdate = strtotime("16-04-2015");
$date = $today - $chkdate;
echo floor($date/(60*60*24));
?>
Please use this may this help you

How to check whether the date coming in $_POST array is not greater than today's date in PHP?

The date to be checked is as follows :
$submission_date = 12-25-2014; //The date in mm-dd-yyyy format that is to be tested against today's date
Now I want to echo the error message since the date contained in a variable $submission_date is a future date.
How should I do this efficiently and effectively using PHP?
Thanks in advance.
Many ways to do this (use DateTime::createFromFormat() to control exact format of input dates, for example) but perhaps the simplest that suits the example is:
$isFuture = (strtotime($submission_date) > strtotime($_POST['current_date']))
Note that OP changed the question. If desired date to test against is not in $_POST array, just replace strtotime($_POST['current_date']) with time() to use current system time.
To compare against current date, disregarding time of day, use:
$today = new DateTime(date("Y-m-d"));
// $today = new DateTime("today"); // better solution courtesy of Glavić
// see http://php.net/manual/en/datetime.formats.relative.php for more info
$today_timestamp = $today->getTimestamp();
If posted format is in m-d-Y, then you cannot convert it to unix timestamp directly with strtotime() function, because it will return false.
If you need to use strtotime() then change the input format to m/d/Y by simple str_replace().
On the other hand, you could use DateTime class, where you can directly compare objects:
$submission_date = DateTime::createFromFormat('!m-d-Y', $submission_date);
$today_date = new DateTime('today');
if ($submission_date > $today_date) {
echo "submission_date is in the future\n";
}
demo
With PHP DateTime you can check whether the input date is future or old w.r.to the todate.
$submission_date = DateTime::createFromFormat('m-d-Y', $submission_date);
$submission_date = $submission_date->format('Y-m-d');
$current_date = new DateTime('today');
$current_date = $current_date->format('Y-m-d');
if ($submission_date > $current_date)
{
echo "Future date";
}
else
{
echo "Old date";
}

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

Categories