I can't seem to get this to work. I have tried from the samples online but there wasn't one the is exactly what I needed. Basically I want to be able to display the number of days that passed from the given date. My sample below is a combined HTML and PHP, I had to do it this way for some reasons.
<?php
$OldDate = strtotime($row['DateSigned']);
$NewDate = date('M j, Y', $OldDate);
?>
<b>Date Signed:</b> <?php echo $NewDate; ?>
<b>Days Since Signed:</b> <?php echo date_diff(strtotime($NewDate),Date("y/m/d")); ?>
This seem to fail.Date("y/m/d") is the date today. Can you tell me what went wrong?
This will work:
<?php
$OldDate = strtotime("2015-10-21");
$NewDate = date('M j, Y', $OldDate);
$diff = date_diff(date_create($NewDate),date_create(date("M j, Y")));
?>
<b>Date Signed:</b> <?php echo $NewDate; ?>
<b>Days Since Signed:</b> <?php echo $diff->format('%R%a days'); ?>
using date_diff, it expects a DateTime object rather than an integer. Here is an example to get you where you may want to be
<?php
$OldDate = new DateTime('2009-10-11');
$now = new DateTime(Date('Y-m-d'));
print_r($OldDate->diff($now));
?>
This outputs (as of the day of this post) ::
[y] => 6
[m] => 0
[d] => 14
[h] => 0
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 2205
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
See DateTime::diff
Below is code that will get you the date difference with current date, i hope it helps.
$date = $row['DateSigned'];
$diff = date_diff(date_create($date), date_create(date('Y-m-d')));
echo $diff->format("%a");
The result you will get is number of days.
Thanks everyone, I found a simpler solution (Simpler for beginner like me to understand) :)
$now = time(); // or your date as well
$your_date = strtotime($NewDate);
$datediff = ceil(($now - $your_date)/86400);
$datediff is now showing the number of days.
It's too late to reply and there are other good answer but I would like to share what worked for me.
date_default_timezone_set("Asia/Karachi");
$old_date = new DateTime('2018-12-01 04:10:58');
$now = new DateTime(Date('Y-m-d'));
$interval = $old_date->diff($now);
echo $interval->d.' days<br>';
// you can also get years, month, hours, minutes, and seconds
echo $interval->y.' years<br>';
echo $interval->m.' months<br>';
echo $interval->h.' hours<br>';
echo $interval->i.' minutes<br>';
echo $interval->s.' seconds<br>';
Try to use timestamps.
$from = mktime(0,0,0,6,1,2015); // example old date
$to = time(); // now
echo round(($to - $from)/86400); // gives you elapsed days
86400 is the # of seconds in a day.
Related
I would like to calculate days based on two dates but it's given incorrect count of days.
I have 2 variables
$date=$date[1]; Is coming from Database
$now =date('d/m/Y'); Current date
$date variable value is(comes from db) 05/03/2019
I used following script for count days based on two dates but its return 120 days.
Method 1
$date=$date[1]; `Is coming from Database`
$now =date('d/m/Y');
$date1 = new DateTime($now);
$date2 = new DateTime($date);
$diff = $date2->diff($date1)->format("%a");
Method 2
$datetime1 = new DateTime($now);
$datetime2 = new DateTime($date);
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
But it's returns wrong days in following output
Difference: 0 years, 4 months, 120 daysDateInterval Object
(
[y] = 0
[m] = 4
[d] = 0
[h] = 0
[i] = 0
[s] = 0
[invert] = 0
[days] = 120
)
Why this given wrong output of days ?
If you use 'd/m/Y' format you should use createFromFormat function to convert string date to date object. For example:
$date1 = new \DateTime();
$date2 = \DateTime::createFromFormat('d/m/Y', '05/03/2019');
$diff = $date2->diff($date1)->format("%a");
While using strtotime function , if i am giving +48 day i am not sure whether is working fine or not ?
<?php
date_default_timezone_set('Asia/Kolkata');
$Seconds = 8604800 ;
$At = "2018-11-28 12:16:19";
echo date('Y-m-d H:i:s',strtotime("+48 day",strtotime($tAt)));
?>
strtotime expects the first parameter to be a valid time string. You are providing the number of seconds. Try -
echo $requestValidTill = date('Y-m-d H:i:s',strtotime("+$resetPasswordDurationInSeconds SECONDS",strtotime($requestAt)));
Output
2018-12-05 12:16:19
strtotime()
Working code
if you have PHP 5.3+ you can use the following lines of code
$requestAt = "2018-11-28 12:16:19";
$resetPasswordDurationInSeconds = 604800 ; //60 * 60 * 24 * 7 ( +7 days in seconds )
$date = new DateTime($requestAt );
$date->add(new DateInterval('PT'.$resetPasswordDurationInSeconds.'S')); // adds 604800 secs
echo date('Y-m-d H:i:s', $date->getTimestamp());
Your just need to add seconds in strtotime
<?php
$requestAt = strtotime("2018-11-28 12:16:19");
$requestAt += 604800;
echo date('Y-m-d H:i:s', $requestAt);
?>
Live Demo
I want to count the total number of days between two date.
Note: I am not talking about the difference between two date
I found lots of answer on google and Stack Overflow. I am sharing here
$now = time(); // or your date as well
$your_date = strtotime("2018-06-01");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
Output is 9
$now = strtotime("2018-06-09");
$your_date = strtotime("2018-06-01");
$datediff = $now - $your_date;
echo $numberDays= round($datediff / (60 * 60 * 24));
Output is 8
$dStart = new DateTime('2018-06-01');
$dEnd = new DateTime('2018-06-09');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->days;
Output is 8
$date1=date_create("2018-06-01");
$date2=date_create("2018-06-09");
$diff=date_diff($date1,$date2);
echo $diff->format("%a");
Output is 8
$startTimeStamp = strtotime("2018-06-01");
$endTimeStamp = strtotime("2018-06-09");
$timeDiff = abs($endTimeStamp - $startTimeStamp);
$numberDays = $timeDiff/86400; // 86400 seconds in one day
// and you might want to convert to integer
echo $numberDays = intval($numberDays);
Output is 8
The correct answer for me is the first one 9 because it displays the total number of days from 1 to 9, not a difference.
I just want to know how to get the count because I don't want to use the time() because it's taking the current date.
For example: If I select the first date 2018-05-01 and my second date in 2018-05-31. So total days is 31, not 30.
Example:
I am working on a project which is related to the working days and salary. So employee will select the date. for example. I am the employee and in the last month May, I select the date 2018-05-01 and 2018-05-31 so I have to display the total working days.So the according to the date I worked 31 days and using above code in the question I am getting 30 days.
Hope you understand my issue. Would you help me out in this?
You can try this-
$dateOne = new DateTime("01-01-2018");
$dateTwo = new DateTime("09-06-2018");
echo $diff = $dateTwo->diff($dateOne)->format("%a");
Output- 159
Use the DateTime class and compare them via diff() method. $date1->diff($date2). The output will give you an accurate result of days:
$date1 = new DateTime('2018-01-01');
$date2 = new DateTime('2018-02-15');
print_r($date1->diff($date2));
Output:
DateInterval Object
(
[y] => 0
[m] => 1
[d] => 14
[h] => 0
[i] => 0
[s] => 0
[f] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 45
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
Output : 272 days.
You can try this:
<?php
$start_date = "2020-12-24";
$end_date = "2020-12-31";
$dateDiff = strtotime($end_date) - strtotime($start_date);
$numOfDays = $dateDiff / 86400;
echo $numOfDays;
?>
Output: 7
First compile and print $now and write down out put after some minutes 2nd time compile and print $now you will ge a difference
here i got your solution in first program php time(); function is dynamically change as per current time in millisecond (In PHP you can simply call time() to get the time passed since January 1 1970 00:00:00 GMT in seconds) here you are using round function to get rounded value after 12pm it your calculation will increase more then 8.5 and you get a rounded value which is 9
here brief explanation Getting unix timestamp in milliseconds in PHP5 and Actionscript3
in rest of program you are taking static time or custom time which are not effected by system time
$now = time(); // or your date as well
$your_date = strtotime("2018-06-01");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
try above program before 12pm maybe you got your answer
I try to write a script that can calculate the difference between two dates, in days, and the diff does not behave as I need to.
More specific, lets say we have the following two date/times:
2015-03-18 23:00
2015-03-19 02:00
The actual time difference is four hours, and in this terms the diff works fine !
But what I like to know is, if the calendar date has been change, and what is the actual difference.
So in the example above, the calendar dates having 1 day difference.
In the following example
2015-03-18 23:00
2015-03-21 02:00
I have three days difference. So how can I calculate this date difference ?
At the moment I use the following code:
$datetime1 = new DateTime('2009-10-11 23:30');
$datetime2 = new DateTime('2009-10-12 02:30');
$interval = $datetime1->diff($datetime2);
echo "<pre>";
print_r($interval);
echo "</pre>";
and the result is the following:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 3
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 0
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
Is there any idea ? Thanks ...
A really simple solution
Notice: this will only work if the days are in the same month.
$datetime1 = new DateTime('2015-03-18 23:00');
$datetime2 = new DateTime('2015-03-21 02:00');
$difference = $datetime2->format('d') - $datetime1->format('d'); //3
Clean solution
You could remove everything from the date, but the year, month and day and use diff() as you already did.
$datetime1 = new DateTime('2015-03-18 23:00');
$datetime2 = new DateTime('2015-03-21 02:00');
$datetime1modified = new DateTime($datetime1->format('Y-m-d'));
$datetime2modified = new DateTime($datetime2->format('Y-m-d'));
$difference = $datetime1modified->diff($datetime2modified)->d; //3
you surely could use a function like this:
$time1 = strtotime("2008-12-13 10:42:00");
$time2 = strtotime("2010-10-20 08:10:00");
$diff = $time2-$time1;
// the difference in int. then you can divide by 60,60,24 and
// so on to get the h:m:s out of it
or if you more into the build in php functions then something like this might suit your needs:
$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');
$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');
best regards.
What you can do is remove the Time from each of the dates and then calculate.
example:
$datetime1 ='2009-10-11 23:30';
$datetime2 = '2009-10-12 02:30';
$date1_explode = explode($datetime1,' ');
$date1_explode = explode($datetime1,' ');
$date = $date1_explode[1];
$date = $date2_explode[1];
$date1 = new DateTime($datetime1);
$date2 = new DateTime($datetime1);
$interval = $date1->diff($date2);
echo "<pre>";
print_r($interval);
echo "</pre>";
If you don't care about the hours and want to know only if the date changed you can try to diff the dates after you set them to the same hour:
$datetime1 = new DateTime('2009-10-11 23:30');
$datetime2 = new DateTime('2009-10-12 02:30');
// Work on duplicates to not change the original objects if they are needed later
$date1 = clone $datetime1;
$date2 = clone $datetime2;
// Set the same hour on both $date1 and $date2
$date1->setTime(0, 0, 0);
$date2->setTime(0, 0, 0);
// Now you can simply compare $date1 to $date2 to see if they are equal
if ($date1 == $date2) {
echo('$datetime1 and $datetime2 are on the same date.');
} else {
echo('$datetime1 and $datetime2 are on different dates.');
}
// Or you can compute the difference
$diff = $date2->diff($date1);
// and format it as you like
echo('There are '.$diff->format('%d').' days between '.$date1.' and '.$date2);
I'm a little unsure why this is not able to find the last day of the previous month. Every steps seems to be working correctly, except when the final date is created.
<?php
$currentMonth = date('n');
$currentYear = date('Y');
if($currentMonth == 1) {
$lastMonth = 12;
$lastYear = $currentYear - 1;
}
else {
$lastMonth = $currentMonth -1;
$lastYear = $currentYear;
}
if($lastMonth < 10) {
$lastMonth = '0' . $lastMonth;
}
$lastDayOfMonth = date('t', $lastMonth);
$lastDateOfPreviousMonth = $lastYear . '-' . $lastMonth . '-' . $lastDayOfMonth;
$newLastDateOfMonth = date('F j, Y', strtotime($lastDateOfPreviousMonth));
?>
$lastDateOfPreviousMonth is returning 2012-09-30 as expected; however, after trying to convert it to September 30, 2012 - $newLastDateOfMonth is returning October 1, 2012. Where do I seem to be going wrong?
EDIT: If using date("t/m/Y", strtotime("last month")); or date('Y-m-d', strtotime('last day of previous month')); will either of these still be viable given 2013-01-01, i.e. will they account for the change in year?
echo date('Y-m-d', strtotime('last day of previous month'));
//2012-09-30
or
$date = new DateTime();
$date->modify("last day of previous month");
echo $date->format("Y-m-d");
Later edit: php.net documentation - relative formats for strtotime(), DateTime and date_create()
There is a php function for this.
echo date("t/m/Y", strtotime("last month"));
First day of this month, minus 1 second.
echo date('Y-m-d',strtotime('-1 second',strtotime(date('m').'/01/'.date('Y'))));
Example here.
please try with below answer.
code:
echo date("t/m/Y", strtotime(date('Y-m')." -1 month"));
You will get last day of previous 12 months.
Example:
<?php
for ($i = 1; $i <= 12; $i++) {
$months[] = date("t/m/Y l", strtotime(date('Y-m')." -$i months"));
}
print_r($months);
?>
Output:
Array
(
[0] => 30/11/2018 Monday
[1] => 31/10/2018 Friday
[2] => 30/09/2018 Wednesday
[3] => 31/08/2018 Sunday
[4] => 31/07/2018 Thursday
[5] => 30/06/2018 Tuesday
[6] => 31/05/2018 Saturday
[7] => 30/04/2018 Thursday
[8] => 31/03/2018 Monday
[9] => 28/02/2018 Monday
[10] => 31/01/2018 Friday
[11] => 31/12/2017 Tuesday
)
You can use strtotime()'s zero handling functionality to achieve this also:
# Day Before
echo date('Y-m-d', strtotime('2016-03-00')); // 2016-02-29
# Year can be handled too
echo date('Y-m-d', strtotime('2016-01-00')); // 2015-12-31
# Month Before
echo date('Y-m-d', strtotime('2016-00-01')); // 2015-12-01
# Month AND Day
echo date('Y-m-d', strtotime('2016-00-00')); // 2015-11-30
Makes sense if you think of 00 as 'one less than the first (01)'.
So to achieve the objective of this question, 'last day of previous month' is a simple case of
date('your_format', strtotime('YYYY-ThisMonth-00'));
# So:
date('Y-m-d', strtotime('2016-11-00')); // 2016-10-31