Okay! so we all have seen how to get days remaining between NOW and a DATE in the future Like I have in my simple code below:
SAY: $endate = a date in future (5 days from today);
$start = new DateTime();
$end = new DateTime($enddate);
$diff = $end->diff($start)->format('%a');
$days = intval($diff);
echo $days.'Days Remaining'; // 5 days Remaining
The above PHP Code is expected to show you how many days are left between NOW and the FUTURE DATE.
But what I want is the reverse of this situation. That is.
instead of having
5 Days Remaining
I need some thing like
0 Day(s) Spent //where today is day 0 of 5
$start = new DateTime("2021-12-14");
$now = new DateTime();
$now_diff = $now->diff($start)->format("%a");
print_r($now_diff .' Day(s) Spent');
Finding the number of days between two dates
CLUE TO ANSWER PROVIDED BY #KHIMAJI VALUKIYA in comment
The trick here is to set the start date not as current date but the actual date to start counting/calculating from.
Then the end date should be set to the current date.
$start = new DateTime($enddate); //date to start counting from
$end = new DateTime(); //current date
$diff = $end->diff($start)->format('%a');
$days = intval($diff);
echo $days.'Days Spent'; // 5 Days Spent
Related
I know this has been asked many times over the years, but I still get different results than what I think should be right. I have the following code that calculates the amount of days between two dates and then it converts it to years and days. When I convert result isn't what I expect. See below. Please let me know what is incorrect, this is really frustrating.
Thanks!
$born = '1985-09-09';
$date = date('Y-m-d H:i:s'); // this is today's date
$birthdate = new DateTime("$born");
$today = new DateTime("$date");
$diff = $today->diff($birthdate)->format("%a");
$days = $diff;
$years_remaining = intval($days / 365); //divide by 365 and throw away the remainder
$days_remaining = $days % 365;
echo "<b>Age:</b> ".$years_remaining."y-".$days_remaining."d<br />";
What I want to appear:
Age: 35y-0d
But what I get:
Age: 35y-9d
Because leap years contains 366 days you can't just divide days/365:
<?php
$born = '1985-09-05';
$date = date('Y-m-d H:i:s'); // this is today's date
$birthdate = new DateTime("$born");
$today = new DateTime("$date");
// get diff in full years
$diff_years = $today->diff($birthdate)->format("%y");
// add years diff to birthday, (so here your last birthday date)
$birthdate->add(new DateInterval("P{$diff_years}Y"));
// count days since your last birthday party day
$diff_days = $today->diff($birthdate)->format("%a");
echo "Age: ".$diff_years."y and ".$diff_days." days ";
Here you can try live PHP code
I'm trying to make some stats for my website.
But I have the problem that if I use the code I got now, when it is a dy like today, so the first day of the month, I got the error division by zero.
My code:
$begin = date('Y-m-01');
$end = date('Y-m-t');
$begin = new \DateTime($begin);
$end = new \DateTime('now');
$diff = $end->diff($begin); // creates a DateInterval object
$days = (int)$diff->format('%a'); // %a --> days
$average_visits = $get_visits / $days;
It does work, when the day isn't 01 or 1.
How can I fix his issue?
It is because $days actually is zero!
Explanation
Today is 2015-07-01 (at least here at my timezone)
you define $begin = date('Y-m-01'); which is 2015-07-01
you define $end = new \DateTime('now'); which is 2015-07-01
you want to know the difference in days which is 0
$diff = $end->diff($begin);
$days = (int)$diff->format('%a');
you divide a unknown number $get_visits by $days (which is zero).
So you get the correct error division by zero.
Possible Solution
If you mean that $days fully includes the beginning day and the end day then use
$days = (int)$diff->format('%a') + 1;
Then
a) begin = 2015-07-01, end = 2015-07-01
b) begin = 2015-07-01, end = 2015-07-05
a) means this is 1 day
b) means these are 5 days (day 2015-07-01, day 2015-07-02, day 2015-07-03, day 2015-07-04 and day 2015-07-05 makes 5 days)
I am creating a website that allow deliveries only within certain delivery time frames.
Here is an example of exactly what I'm looking for:
FakeCompany delivers on Wednesday and allows customers to place orders between Friday and Tuesday with a cutoff time of 11 PM on Tuesday night.
I need to figure out when the customer logs in if ordering is allowed (between Friday - Tuesday 11 PM). I also need to know how much longer they have to order.
I know the PHP date('N') function that Friday is 5:
date('N', strtotime('Friday'));
and Tuesday is 1:
date('N', strtotime('Tuesday'));
These time ranges may change, so I need a simple solution.
Here is what I started with, and now I'm lost on how to do this.
//Set today and get from database start / end days and end time
$today = (int)date('N');
$startDay = (int)date('N', strtotime('Friday'));
$endDay = (int)date('N', strtotime('Tuesday'));
$endDayTime = '11:00:00';
//If today is before start date
if($today >= $startDay && $today <= $endDay){
//This works only if the end date is not the following week
//It also needs to be before end day time!
}
I think I need to get the date of the week based on the DAY (Friday) and convert that to this weeks Friday if Friday has not passed or next weeks Friday and do the same with end date.
Then I need to know if today is between those dates / times.
$now = new DateTime();
$tuesday = new DateTime('last Tuesday');
$friday = new DateTime('Friday 11pm');
if ($tuesday < $now && $now < $friday) {
$interval = $friday->diff($now);
echo $interval->format('%d day %h hours %i minutes left to order');
}
else {
echo "you can't order now";
}
See it in action
Here is a function to check that today is an approved day then if its tuesday also make sure it is before 11pm:
/*
Acceptable days:
5 - friday
6 - saturday
7 - sunday
1 - monday
2 - tuesday
*/
//Can they order today?
if(in_array(date('N'),array(1,2,5,6,7))){
//if today is tuesday is it before 11pm?
if(date('N') == 2){
if(date('H')<23){
//23 = 11pm in 24 hour time
//Then can order
}
else{
//Then CANT order
}
}
//Its not tuesday so we dont care what time it is they can order
}
for the end day I think you could do it like this:
$endDay = (int)date('N', strtotime('Friday') + 3 * 24 * 3600 + 23 * 3600);
strtotime('Friday') to get friday and add 3 days of 24 hours to it, and it'll be Tuesday 0 am. Then you add 23 hours time to it as it finish at 11pm.
$today = (int)date('N');
$startDay = (int)date('N', strtotime('Friday'));
$endDay = (int)date('N', strtotime('Friday') + 3 * 24 * 3600 + 23 * 3600);
//If today is before start date
if($today >= $startDay && $today <= $endDay){
//now it works
}
Here is exactly what I am looking for.
The dates provided may not be this week or even this month, so we need to figure out based on the date what the day of the week was and set the date on this week or next week to same day depending on today (kinda confusing).
See It In Action
//IF USING A DATABASE TO STORE DATE/TIME
//Get route times
//When Using Database: $query = "SELECT * FROM routes WHERE id = '".$user['route_one']."'";
//When Using Database: $result = $this->query($query);
//When Using Database: $route = $this->fetchArray($result);
//Set date vaiables
$thisWeek = new DateTime();
$routeStart = new DateTime(date('Y-m-d H:i:s', strtotime('2013-04-21 00:00:00')));
//When Using Database: $routeStart = new DateTime(date('Y-m-d H:i:s', strtotime($route['start_time'])));
$routeEnd = new DateTime(date('Y-m-d H:i:s', strtotime('2013-04-24 00:00:00')));
//When Using Database: $routeEnd = new DateTime(date('Y-m-d H:i:s', strtotime($route['end_time'])));
$interval = $routeStart->diff($routeEnd);
$numDays = abs($interval->format('%d'));
//Check if today is past or on the start date, else start date is next week, and set day of week
if($thisWeek->format('N') >= $routeStart->format('N')){
$startDate = $thisWeek->modify('last '.$routeStart->format('l'));
}
else{
$startDate = $thisWeek->modify($routeStart->format('l'));
}
//Now that we know the start date add the amount of days to the start date to create the end date
$endDate = new DateTime($startDate->format('Y-m-d H:s:i'));
$endDate->modify('+'.$numDays.' days '.$routeEnd->format('H').' hours');
//Check to see if user is within the time range to order or not
$today = new DateTime();
if($startDate <= $today && $today <= $endDate){
//Find out how much longer ordering can take place
$interval = $endDate->diff($today);
$output = 'Allowed to order!<br>';
$output .= '<div id="orderTimeCounter">'.$interval->format('%d days %h hours %i minutes left to order').'</div>';
}
else{
//If today is before start date set start date to THIS week otherwise NEXT week
if($startDate >= $today){
$startDate = $startDate->modify('this '.$routeStart->format('l'));
}
else{
$startDate = $startDate->modify('next '.$routeStart->format('l'));
}
//Find out how much longer until ordering is allowed
$interval = $today->diff($startDate);
$output = 'Not allowed to order!';
$output .= '<div id="orderTimeCounter">'.$interval->format('%d days %h hours %i minutes until you can order').'</div>';
}
echo $output;
I'm calculating the difference between 2 dates using DateTime() and it's working fine. The problem is that I want to have the days format be able to go above a full month so 30/31 or higher.
$now = new DateTime();
$future_date = new DateTime($contest->expires_at);
$interval = $future_date->diff($now);
$enddate = $interval->format("%m month, %d days, %h hours, %i minutes");
The current problem with this is that when I don't display the months, the days can only go up to 30/31 and anything over that will be carried over to make a new month resetting the days count with the leftover days.
I want to be able to display 42 days when the difference is 6 weeks with this kind of format:
$enddate = $interval->format("%d days, %h hours, %i minutes");
Is there a quick fix for this or do I need to manually convert the timestamp to seconds and use my own function with modulus operators for this?
You can try:
$enddate = $interval->format("%a days, %h hours, %i minutes");
See the DateInterval::format in the manual.
NOTE
Take care of the bug if you're working on windows.
This should solve your porblem:
$now = new DateTime();
$future_date = new DateTime();
// a period of 2 months
$addPeriod = new DateInterval('P2M');
// adding the period
$future_date->add($addPeriod);
// get the differnce
$interval = $future_date->diff($now);
echo($interval->days) . ' days';
For today: echo returns '61 days'
// EDIT
To avoid running into the dataInterval-Bug you can use:
$now = new DateTime();
$future_date = new DateTime();
// a period of 2 months
$addPeriod = new DateInterval('P2M');
// adding the period
$future_date->add($addPeriod);
// get the difference in second
$diffTimestamp = $future_date->getTimestamp() - $now->getTimestamp();
// convert to days
// 1 day = 86.400 seconds
$diffDays = $diffTimestamp/86400;
echo(floor($diffDays)) . ' days';
Update my php version since this is a bug in my old and it works perfectly now.
How to get aggregate days from PHP's DateTime::diff?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP last day of the month
Is there any function like $date->getMonthDays() or $date->getLastDayOfMonth() in PHP to get the number of days in a given month (or the last day number)?
$start = new DateTime('2012-02-01');
$end = clone $start;
// Interval = last day of the month minus current day in $start
$interval = $start->getLastDayOfMonth() - intval($start->format('j'));
$end->add(new DateInterval('P' . $interval . 'D'));
EDIT: thanks, voted to close, it's a duplicate, sorry for asking...
The php date function gives you the number of days in the month with 't'
date("t");
See: http://php.net/manual/en/function.date.php
It's simple to get last month date
echo date("Y-m-t", strtotime("-1 month") ) ;
echo date("Y-m-1", strtotime("-1 month") ) ;
at March 3 returns
2011-02-28
2011-02-1
t gives you the total number of days in the current month. j gives you the current day of the month.
Using modify and some subtraction from format-ing the datetime, you can get to the end of the month.
$date = new DateTime();
$lastDayOfMonth = $date->modify(
sprintf('+%d days', $date->format('t') - $date->format('j'))
);