Find date difference in php? - php

Is there anyway to find the date difference in php? I have the input of from date 2003-10-17 and todate 2004-03-24. I need the results how many days is there within these two days. Say if 224 days, i need the output in days only.
I find the solution through mysql but i need in php. Anyone help me, Thanks in advance.

$start = new DateTime( '2003-10-17' );
$end = new DateTime( '2004-03-24' );
$diff = $start->diff( $end );
echo $diff->format( '%d days' );
...should do it.
For reference see DateTime and DateInterval.
Mind you though, this is only available as of PHP 5.3.

You can use the parse timestamp feature to convert dates to timestamps, subtract the timestamps, and then convert the resulting timestamp (seconds) to days:
floor((strtotime("2004-03-24") - strtotime("2003-10-17"))/86400);

Example is as below:
$startDate = new DateTime( '2013-04-01' ); //intialize start date
$endDate = new DateTime( '2013-04-30' ); //initialize end date
$holiday = array('2013-04-11','2013-04-25'); //this is assumed list of holiday
$interval = new DateInterval('P1D'); // set the interval as 1 day
$daterange = new DatePeriod($startDate, $interval ,$endDate);
foreach($daterange as $date){
if($date->format("N") <6 AND !in_array($date->format("Y-m-d"),$holiday))
$result[] = $date->format("Y-m-d");
}
echo "<pre>";print_r($result);
A detail blog is here: http://goo.gl/YOsfPX

Related

PHP - Fetch all dates between two dynamic UNIX timestamps [duplicate]

This question already has answers here:
PHP: Return all dates between two dates in an array [duplicate]
(26 answers)
Closed 4 years ago.
I want to get all the dates between two given specific dates which will be changing dynamically according to the user requirements.
This works fine for me :
$begin = new DateTime( '2018-07-01' );
$end = new DateTime( '2018-08-10' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
$dates = [];
foreach($daterange as $date){
array_push($dates,$date->format('Y-m-d'));
}
return $dates;
But this gives me NULL array when I insert dates dynamically. For example,
$begin = new DateTime($request->date1);
$end = new DateTime(today());
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
$dates = [];
foreach($daterange as $date){
array_push($dates,$date->format('Y-m-d'));
}
return dates;
I have tried many inputs like storing today's date in a variable, changing it's format and then using that variable as an input. I tried changing date variable to string using (string) function and also I have used Carbon classes for dates, but somehow I am making mistake using DateTime, DateInterval and DatePeriod as I don't know the basics of them.
I need to get all the dates between two specific dates for charts in my admin panel.
Finally got the solution for this question. It worked by converting the dates to UNIX timestamp. Here's the code, how it worked:
$date_from = "2018-07-01";
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp
// Specify the end date. This date can be any English textual format
$date_to = strtotime(today()); // Convert date to a UNIX timestamp
$dates = [];
// Loop from the start date to end date and output all dates inbetween
for ($i=$date_from; $i<=$date_to; $i+=86400) {
array_push($dates,date("Y-m-d", $i));
}
return $dates;
Here is the reference where I found this solution, hope this helps others too.

Include last date in range between dates in php

I have found a problem with using DatePeriod which might be because I am stupid lol.
As you can see I have added +1 to my end date because I want to include the last date of the range.
But my issue is when I have ending date 31 it makes it to 32 which is not a date so it throws out an error.
Is there a way to include the ending date or to make the +1 work?
$period = new DatePeriod(
new DateTime($event['startyear'].$event['startmonth'].$event['startdate']),
new DateInterval('P1D'),
new DateTime($event['endyear'].$event['endmonth'].$event['enddate'] +1)
);
foreach ($period as $savedDate) {
echo $savedDate;
}
You should create the date object for the initial date (without the +1) and then increment the day of that object by 1 day.
For example:
$date1 = new DateTime($event['endyear'].$event['endmonth'].$event['enddate']);
$date2 = new DateTime($event['endyear'].$event['endmonth'].$event['enddate']);
$date2->modify('+1 day');
$period = new DatePeriod($date1, new DateInterval('P1D'), $date2);
What about this:
$endDate = mktime(0,0,0, $event['endmonth'], $event['enddate'], $event['endyear']);
$counter = 0;
while($endDate >= $date = mktime(0,0,0, $event['startmonth'], $event['startdate']+$counter++, $event['startyear']) ) {
echo date('Y/m/d', $date);
}

How to find 1 day ago in date('m.d.Y') in PHP? v5.1.6

Whats the best method to find the date in date('m.d.Y') format that is 1 day ago from another date in date('m.d.Y') format in PHP? Must be applicable to v5.1.6.
I need to build a recursive method to iterate through previous days.
Thanks!
------------Revision -------
$date = date('m.d.Y');
$date = date('m.d.Y', strtotime($date .' -1 day'));
The doesn't seem to work :(
The date must begin and end in the same format 'm.d.Y'
You really should be looking at using DateTime, DateInterval, and DatePeriod classes for this. As an example:
$start_date = '12.31.2013'; // your input date
$start_date_time = DateTime::createFromFormat('m.d.Y', $start_date);
$one_day_interval = new DateInterval('P1D');
// iterate X number of days example
$iteration_days = 30; // some value for number of iterations you want
$count_period = new DatePeriod($start_date_time, $one_day_interval, $iteration_days);
foreach($count_period as $day) {
// do something
}
// iterate between start and end date example
$end_date = '3.31.2014';
$end_date_time = DateTime::createFromFormat('m.d.Y', $end_date);
$date_period = new DatePeriod($start_date_time, $one_day_interval, $end_date_time);
foreach($date_period as $day) {
// do something
}
$date = DateTime::createFromFormat('m.d.Y', $yourDate);
$date->sub(new DateInterval('P1D');
try like this:
$date =date("Y-m-d"); //set your date
echo date('m.d.Y', strtotime($date .' -1 day'));
demo : https://eval.in/107144

get all weekdays in php [duplicate]

This question already has an answer here:
PHP: getting weekdays numbers of a given month
(1 answer)
Closed 10 years ago.
I am thingking if how to get all the date of weekdays between a given date
example: I have a date given 2013-01-01 and 2013-20-01
It must return all date of weekdays like 2013-01-01
how could this be done using php
thankz
Look into DatePeriod Class, this is available from PHP 5.3.
Here is an example from the site
$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
// You can manipulate the date here
echo $date->format("Ymd") . "<br>";
}
You can get the weekday from the timestamp using the multitude of formatting options avalaible:
echo date("D",strtotime("2013-01-01"));
tues

How to iterate, by month, between two specified dates

I have a website that was launched a few months ago. I would like to write some code that will look through every month, since launch, and grab metrics for that month.
My question is: What is the best way to specify a start date, and then iterate by month, all the way up until the current month (or to another specified date).
Does anyone have any suggestions? I'm using PHP and a mySQL database.
You could use strtotime, to increment the date by +1 month:
$date1 = strtotime('2009-01-01');
$date2 = strtotime('2010-01-01');
while ($date1 <= $date2) {
echo date('Y-m-d', $date1) . "\n";
$date1 = strtotime('+1 month', $date1);
}
And if you have PHP >= 5.3.0, you can use DateTime::add with an DateInterval object
Check the above example here.
I have a method which is optimal in results :
$begin = new DateTime( '2014-07-14' );
$end = new DateTime( '2014-08-01' );
$end = $end->modify( '+1 month' );
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($begin, $interval, $end);
foreach($period as $dt) {
var_dump($dt->format( "m" ));
}
Hope this will help.
If you start from last day of a 30 days month, you may lose some month in between using "+1 month". Try from 2015-06-30 to 2015-12-31 for example, it will skip september 2015.
Instead of using "+1 month", I suggest to use "first day of next month" instead:
$begin = new DateTime( '2015-06-30' );
$end = new DateTime( '2015-12-31' );
$end = $end->modify( 'first day of next month' );
$interval = DateInterval::createFromDateString('first day of next month');
$period = new DatePeriod($begin, $interval, $end);
foreach($period as $dt) {
var_dump($dt->format( "m" ));
}
this will list september 2015 as well.
I don't know the schema of your stored metrics, so here's a generic example:
Select total pageviews per month from Aug 1 thru Nov 30 2009
The code for MySQL:
SELECT DATE_FORMAT(s.date, '%Y-%m') AS year_month , SUM( s.pageviews ) AS s.pageviews_total
FROM statistics s
WHERE s.date BETWEEN '2009-08-01' AND '2009-11-30'
GROUP BY DATE_FORMAT(s.date, '%Y-%m')
ORDER BY DATE_FORMAT(s.date, '%Y-%m')
Having that aggregated table output may be enough for you. If not, you can loop through it with PHP and perform other manipulations.
$start_date = mktime(0, 0, 0, 1, 1, 2009);
$end_date = mktime(0, 0, 0, 10, 1, 2009);
$current_date = $start_date;
while($current_date <= $end_date) {
$current_date = strtotime("+1 month", $current_date);
}
That is one way to do it. Another one includes two loops over months and years separately.
But if you are know SQL well, you can get all your metrics and GROUP BY EXTRACT(YEAR_MONTH FROM date) right there in DB, which will most likely be faster.

Categories