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) {
}
Related
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");
}
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;
}
I want to change date var when x days have passed
For instance:
Today is 21.12.16 - $date = '23.12.16'
Tomorrow is 22.12.16 - $date = '23.12.16'
When it's 23.12.16 - $date = '25.12.16'
Her's the code I got so far. Hope this will make some sense
$date = "2016-12-21"; //** will describe this lower
$days_passed = date_create()->diff(date_create($date))->days;
if ($days_passed >= 2){
$new_date = date('d.m.y', strtotime("+2 days"));
} else{
$new_date = $date;
}
This works ok if I just want to do it once
**I need to change this var every 2 days. I understand that i can write it to a Database or to a .txt. But there sure is a way to do this just by php
P.S. sorry for my bad English.
Here's what I came up with:
$date = '2016-12-01'; //Your script start date, you wont need to change this anymore
$everyxdate = 10; // once x days to add x to $date
$days_passed = date_create()->diff(date_create($date))->days; // passed days from start of script $date
$mod_dates = (int)($days_passed / $everyxdate); // count how much cycles have passed
$daystoadd = $mod_dates * $everyxdate + $everyxdate; // count how much days we need to add
$newdate = strtotime ("+$daystoadd day" , strtotime ( $date ) ) ; // Add needed day count to starting $date
$newdate = date ( 'd.m.y' , $newdate ); // Format date the way you want
Hope this will help some one who has the same task I had.
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
i am struggling for a long time to set a specific date but i am not getting correct out put.
i want to get date from user and compare that date with the date 15 days older then today. if it is older than 15 days then convert to today else print what it is.
$todaydate= $_GET['date'];// getting date as 201013 ddmmyy submitted by user
$todaydate=preg_replace("/[^0-9,.]/", "", $todaydate);
$today =date("dmy"); //today ddmmyy
$older= date("dmy",strtotime("-15 day")); // before 15 days 051013
if ($todaydate <= $older){
$todaydate= $today;}
problem is, it is taking date as number and giving wrong result.
Comparing date strings is a bit hacky and prone to failure. Try comparing actual date objects
$userDate = DateTime::createFromFormat('dmy', $_GET['date']);
if ($userDate === false) {
throw new InvalidArgumentException('Invalid date string');
}
$cmp = new DateTime('15 days ago');
if ($userDate <= $cmp) {
$userDate = new DateTime();
}
Also, strtotime has some severe limitations (see http://php.net/manual/function.strtotime.php#refsect1-function.strtotime-notesand) and is not useful in non-US locales. The DateTime class is much more flexible and up-to-date.
try this one:
<?php
$todaydate = date(d-m-Y,strtotime($_GET['date']));
$today = date("d-m-Y");
$older= date("d-m-Y",strtotime("-15 day"));
if (strtotime($todaydate) <= strtotime($older))
{
$todaydate= $today;
}
?>
$previousDate = "2012-09-30";
if (strtotime($previousDate) <= strtotime("-15 days")) {
//the date in $previousDate is earlier or is equal to the date 15 days before from today
}