Comparing dates and show the remainder left til expiry date in PHP - php

I am trying to create an application in PHP that have a subscription period of 14 days. In my db table, I have start date and expiry date. Iam a bit confused to show up the expiration banner that says "Your application will expire in --- days" .
$start = explode(' ', $billing->started_at); // to get the date only
$end = explode(' ', $billing->expires_at);
$date1=date_create($start[0]);
$date2=date_create($end[0]);
$diff=date_diff($date1,$date2);
Session::put('days_left', $diff->format("%R%a days"));
Please help

In theory, your code should work but you didn't tell us what the actual issue is so here's how I'd approach it.
If you only want to calculate using the date portion of your timestamps, you can just format it before creating your DateTime objects.
<?php
$start = new DateTime(date('Y-m-d', strtotime($billing->started_at)));
$end = new DateTime(date('Y-m-d', strtotime($billing->expires_at)));
$difference = $start->diff($end);
echo $difference->format("Your application will expire in %a days.");
Alternatively, you can simply use the timestamp directly. Depends on what you are trying to achieve.
<?php
$start = new DateTime($billing->started_at);
$end = new DateTime($billing->expires_at);
$difference = $start->diff($end);
echo $difference->format("Your application will expire in %a days.");
Working example:
http://sandbox.onlinephpfunctions.com/code/417d4691483f53fe083735d257df4fb49b832c58

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;
}

Next delivery date listed on website

I'm building a website for a business that makes deliveries every second Thursday. I need to display when the next delivery is going to be, and have that date change to two weeks forward when the previous delivery date is reached.
Based on what I've been able to research so far, I've cobbled together this code:
$start_date = '2016-10-27'; // next delivery date to start counting from
// create a DateTime object that represents start of sequence
$start_datetime = DateTime::createFromFormat('Y-m-d', $start_date);
// create a DateTime object representing the current date
$current_datetime = new DateTime('today');
$date_interval = new DateInterval('P2W'); // for delivery every 2 weeks
// determine end date for DatePeriod object that will later be used
// this is no further out than current date plus the interval
$end_datetime = new DateTime('tomorrow');
$end_datetime->add($date_interval);
$date_period = new DatePeriod($start_datetime, $date_interval, $end_datetime);
// iterate until the last date in the set
foreach($date_period as $dp) {
$next_delivery = $dp;
}
?>
<div class="header-next-delivery">
Next delivery: <?php echo $next_delivery->format('l, M j, Y'); ?>
</div>
This seems to work, but I can't help thinking that there must be a more elegant way to do this than having to iterate through a set of dates from the start date to the last date in the set. As time passes, the set will just get bigger and bigger.
Also, I'm having trouble figuring out the internal workings of these functions -- how would I set the exact time that the displayed delivery date bumps forward by two weeks?
Thanks for any insight!
You can get date interval in days from $start_date to current date. Divide it by 14 (two weeks), get remainder and substract it from 14. Then you can add that value of days to current date.
$start_date = date_create('2016-10-27');
$current_date = date_create();
$interval = date_diff($start_date, $current_date);
$days_diff = (int)$interval->format('%a');
$current_date->add(14 - ($days_diff % 14).' days');

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

Date Differnce PHP two changing dates

Basically i have a couple dates that are changed when the next/prev page button is clicked, but i need to cap it so it can only be clicked +/- 7 Days then the button disappears.
here is my controller
$data['date'] = isset($_GET['date']) ? new DateTime($_GET['date']) : new DateTime();
$data['tomorrow'] = new DateTime($data['date']->format('Y-m-d 00:00:00'));
$data['tomorrow']->add(new DateInterval('P1D'));
$data['yesterday'] = new DateTime($data['date']->format('Y-m-d 00:00:00'));
$data['yesterday']->sub(new DateInterval('P1D'));
$data['today'] = date("Y-m-d 00:00:00");
$data['next'] = TRUE;
$data['prev'] = TRUE ;
So if ( date diff of the two dates is more than +/- 7 days ) "die" and buttons dissapear using above variables, we kill page aswell so people cant alter url to access the dates.
If (date diff less than or equal to +/- 6 days) Then show the button
i've tried date_diff but it didnt seem to work , I just need a hand please bare in mind i am an apprentice and have only been using php for 2 months.
You can use the diff method which returns a DateInterval:
<?php
$d1 = new DateTime("2014-03-20");
$d2 = new DateTime();
$dateInterval = $d1->diff($d2);
$nDayBetween = $dateInterval->days;
var_dump($dateInterval);
echo "<br /><br />" . $nDayBetween;

Subtract php format date and set the difference value in a textbox [duplicate]

How can I compute time difference in PHP?
example: 2:00 and 3:30.
I want to convert the time to seconds then subtract them then convert it back to hours and minutes to know the difference. Is there an easier way to get the difference?
Look at the PHP DateTime object.
$dateA = new DateTime('2:00');
$dateB = new DateTime('3:00');
$difference = $dateA->diff($dateB);
(assuming you have >= PHP 5.3)
You can also do it the procedural way...
$dateA = strtotime('2:00');
$dateB = strtotime('3:00');
$difference = $dateB - $dateA;
See it on CodePad.org.
You can get the hour offset like so...
$hours = $difference / 3600;
If you are dealing with times that fall between a 24 hour period (0:00 - 23:59), you could also do...
$hours = (int) date('g', $difference);
Though that is probably too inflexible to be worth implementing.
Check this link ...
http://www.onlineconversion.com/days_between_advanced.htm
I used this to calculate the difference between server time and the users local time. Grab the hour difference and drop that in a form when the user is registering. I then use it to update the time on the site for the user when they do stuff online.
Once I got it working, I switched this line ...
if (form.date1.value == "")
form.date1.value = s;
to ...
form.date1.value = "<?PHP echo date("m/d/Y H:i:s", time()) ?>";
Now I can compare the user time and the server time! You can grab the seconds and mins as well.

Categories