I have $date1 = '2014-09-01' and $date2 = '2015-02-01'. Can I get months and years from $date1 to $date2 like this:
2014-sep
2014-oct
2014-nov
2014-dec
2015-jan
2015-feb
Instantiate DateTime objects and loop through them:
$date1 = new \DateTime('2014-09-01');
$date2 = new \DateTime('2015-02-01');
while ($date1 <= $date2) {
echo $date1->format('Y-M') . '<br>';
$date1->add(new \DateInterval('P1M')); // increase by one month
}
Result:
2014-Sep
2014-Oct
2014-Nov
2014-Dec
2015-Jan
2015-Feb
$date1 = new DateTime("2014-09-01");
$date2 = new DateTime("2015-02-01");
while ($date1 <= $date2) {
echo $date1->format("Y-M")."\n";
$date1->modify("+1 month");
}
Result:
2014-Sep
2014-Oct
2014-Nov
2014-Dec
2015-Jan
2015-Feb
Use DateTime and DateInterval class with couple of methods like add() to increment counter and format() to date formating using simple while loop
$startDate= new DateTime("2014-09-01");
$endDate = new DateTime("2015-02-01");
$oneMonth=new DateInterval('P1M'); //for 1 month interval
while ($startDate <= $endDate) {
print $startDate->format("Y-M")."\n"; //date formating as your requirement
$startDate->add($oneMonth); //increment counter by 1 month
}
Related
What is the best way to compare a month and day date ("m-d") with a date with the format "y-m-d".
for example:
$date1 = "2022-04-20";
$date2 = "2022-05-20";
$seasonStart = "03-15";
$seasonEnd = "04-30";
I want to know how many days between $date1 and $date2 are between $seasonStart and $seasonEnd.
You can use DateTime objects for the comparison.
$date1 = new DateTime($date1);
$date2 = new DateTime($date2);
For the seasonal dates, there are a couple of different ways you can do it depending on how you need it to work.
You can use the year from the given date rather than defaulting to the current year, if you want to see if those dates are within the season for the year in which they occur.
$year = $date1->format('Y');
$seasonStart = new DateTime("$year-$seasonStart");
$seasonEnd = new DateTime("$year-$seasonEnd");
If you only want to compare the date range to the season for the current year, then you can let the year default to the current one.
$seasonStart = DateTime::createFromFormat('m-d H:i', "$seasonStart 00:00");
$seasonEnd = DateTime::createFromFormat('m-d H:i', "$seasonEnd 00:00");
Then you can use this to calculate the number of days in the given range that are included in the season.
if ($date1 > $seasonEnd || $date2 < $seasonStart) {
// in this case the range does not overlap with the season at all
$days = 0;
} else {
$days = (max($seasonStart, $date1))->diff(min($seasonEnd, $date2))->days + 1;
}
<?php
$date = DateTime::createFromFormat('m-d', '02-15');
echo $date->format("Y-m-d");
$season=$date->getTimeStamp();
$current=time();
if ($current>$season) {
echo "Season has started!";
}
?>
I am calculated the date in 6 months time like this...
$date = new DateTime('01/02/2019');
$date->add(new DateInterval('P6M'));
echo $date->format('d/m/Y') . "\n";
This is working as far as I can tell, does anybody know of a way to get it to output an array of dates in this new period?
Does DateTime have anything built in?
You need to loop through all the dates, as there is no native function to do this.
You can create a loop that would append each date to an array, and increment the date until it reaches the end-date.
function get_interval($startDate, $endDate) {
$result = [];
while ($startDate < $endDate) {
$currentDate = (clone $startDate);
$result[] = $currentDate;
$startDate->modify("+1 day");
}
return $result;
}
$date = new DateTime('01/02/2019');
$enddate = (clone $date)->add(new DateInterval('P6M')); // Note that the object is cloned
// Otherwise we modify the original $date
print_r(get_interval($date, $enddate));
Live demo at https://3v4l.org/aLf5o
here i have stored two dates in db like start date as 2014-07-07 00:00:00 and end date as 2014-07-15 23:59:59. Now how can I check my current date between the two days
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$now = new DateTime();
$current_time = $now->format('Y-m-d H:i:s');?>
if date1 and date2 are retrieved from db and compare with current date it getting from server if it is between the two days it should be display end time from now.
USE :
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$cdate1 = new DateTime($date1);
$vdate1 = $cdate1->getTimestamp();
$cdate2 = new DateTime($date2);
$vdate2 = $cdate1->getTimestamp();
compare integers ($vdate1 and $vdate2) to each other
Result will be in seconds
Enjoy :)
Just as an Object Oriented style alternative you can create objects as instances of DateTime class, like these:
$date1 = new DateTime('2014-07-07 00:00:00');
$date2 = new DateTime('2014-07-15 23:59:59');
$now = new DateTime();
then, following your logic, you can compare if now is before or after the other dates, like:
var_dump($date2 > $now);
or you can retrieve an instance of DateInterval interface with:
$now_interval_from_date1 = $date1->diff($now);
and then use the format method to know exactly the time/day/etc.. differences, like:
$now_interval_from_date1->format("%R%H hours")
You can find the format params here:
http://www.php.net/manual/it/dateinterval.format.php
If the two dates are exactly in the same format, php allows string comparison.
So you can do the following:
if(strcmp($date1, $current_time) <= 0 and strcmp($date2, $current_time) > 0)
{
// The date is within the limits
}
strcmp is a safer function for string comparison
So, in your case, you could have the following:
<?php
$con=mysqli_connect("localhost","root","","proms"); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
date_default_timezone_set("America/New_York");
$current_time =date("h:i:sa");
$result = mysqli_query($con,"SELECT * FROM image");
while($row = mysqli_fetch_array($result)) {
if(strcmp($row['start_date'],$current_time) <= 0 && strcmp($row['end_date'],$current_time) > 0) {
// The date is within the limits
echo "yes";
}
}
?>
'start_date' and 'end_date' should be substituted with your fields' names.
You can do as following to compare current time between two dates
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$now = date('Y-m-d H:i:s');
$date1TimeStamp = strtotime($date1);
$date2TimeStamp = strtotime($date2);
$nowTimeStamp = strtotime($now);
if($date1TimeStamp <= $nowTimeStamp || $date2TimeStamp >= $nowTimeStamp){
$seconds_diff = $date2TimeStamp - $nowTimeStamp;
$days = $seconds_diff/(3600*24);
}else
echo 'No, out';
Edited calculation, now it displays remaining days time from now to end date.
if(strtotime('now') > strtotime($date1) && strtotime('now') < strtotime($date2)) {
$diff = strtotime($date2) - strtotime('now');
}
$diff then contains the difference between the two dates in miliseconds. Just convert miliseconds to days : hours : minutes (Mathematics ?)
What's the cleanest way to use a loop in PHP to list dates in the following way?
2011_10
2011_09
2011_08
2011_07
2011_06
...
2010_03
2009_02
2009_01
2009_12
2009_11
The key elements here:
Should be as simple as possible - I would prefer one for loop instead of two.
Should list this month's date as the first date, and should stop at a fixed point (2009-11)
Should not break in the future (eg: subtracting 30 days worth of seconds will probably work but will eventually break as there are not an exact amount of seconds on each month)
Had to make a few tweaks to the solution:
// Set timezone
date_default_timezone_set('UTC');
// Start date
$date = date('Y').'-'.date('m').'-01';
// End date
$end_date = '2009-1-1';
while (strtotime($date) >= strtotime($end_date))
{
$date = date ("Y-m-d", strtotime("-1 month", strtotime($date)));
echo substr($date,0,7);
echo "\n";
}
Maybe this little code does the thing? :
more complicated situations.
<?php
// Set timezone
date_default_timezone_set('UTC');
// Start date
$date = '2009-12-06';
// End date
$end_date = '2020-12-31';
while (strtotime($date) <= strtotime($end_date)) {
echo "$date\n";
$date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
}
?>
The credit goes to: http://www.if-not-true-then-false.com/2009/php-loop-through-dates-from-date-to-date-with-strtotime-function/
This is what im guessing your asking for cause it doesnt really make sense......
$startmonth = date("m");
$endmonth = 7;
$startyear = date("Y");
$endyear = 2012;
//First for loop to loop threw years
for($i=$startyear; $i<=$endyear; $i++, $startmonth=0) {
//Second for loop to loop threw months
for($o=$startmonth; $o<=12; $o++) {
//If statement to check and throw stop when at limits
if($i == $endyear && $o <= $endmonth)
echo $i."_".$o."<br/>";
else
break;
}
}
Will output:
2012_0
2012_1
2012_2
2012_3
2012_4
2012_5
2012_6
2012_7
PHP 5.3 introduces some great improvements to date/time processing in PHP. For example, the first day of, DateInterval and DatePeriod being used below.
$start = new DateTime('first day of this month');
$end = new DateTime('2009-11-01');
$interval = new DateInterval('P1M');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
echo $date->format('Y_m') . PHP_EOL;
}
Let's assume I have two dates in variables, like
$date1 = "2009-09-01";
$date2 = "2010-05-01";
I need to get the count of months between $date2 and $date1($date2 >= $date1). I.e. i need to get 8.
Is there a way to get it by using date function, or I have to explode my strings and do required calculations?
Thanks.
For PHP >= 5.3
$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-05-01");
var_dump($d1->diff($d2)->m); // int(4)
var_dump($d1->diff($d2)->m + ($d1->diff($d2)->y*12)); // int(8)
DateTime::diff returns a DateInterval object
If you don't run with PHP 5.3 or higher, I guess you'll have to use unix timestamps :
$d1 = "2009-09-01";
$d2 = "2010-05-01";
echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30)); // 8
But it's not very precise (there isn't always 30 days per month).
Last thing : if those dates come from your database, then use your DBMS to do this job, not PHP.
Edit: This code should be more precise if you can't use DateTime::diff or your RDBMS :
$d1 = strtotime("2009-09-01");
$d2 = strtotime("2010-05-01");
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$i = 0;
while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
$i++;
}
echo $i; // 8
Or, if you want the procedural style:
$date1 = new DateTime("2009-09-01");
$date2 = new DateTime("2010-05-01");
$interval = date_diff($date1, $date2);
echo $interval->m + ($interval->y * 12) . ' months';
UPDATE: Added the bit of code to account for the years.
Or a simple calculation would give :
$numberOfMonths = abs((date('Y', $endDate) - date('Y', $startDate))*12 + (date('m', $endDate) - date('m', $startDate)))+1;
Accurate and works in all cases.
This is another way to get the number of months between two dates:
// Set dates
$dateIni = '2014-07-01';
$dateFin = '2016-07-01';
// Get year and month of initial date (From)
$yearIni = date("Y", strtotime($dateIni));
$monthIni = date("m", strtotime($dateIni));
// Get year an month of finish date (To)
$yearFin = date("Y", strtotime($dateFin));
$monthFin = date("m", strtotime($dateFin));
// Checking if both dates are some year
if ($yearIni == $yearFin) {
$numberOfMonths = ($monthFin-$monthIni) + 1;
} else {
$numberOfMonths = ((($yearFin - $yearIni) * 12) - $monthIni) + 1 + $monthFin;
}
I use this:
$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-09-01");
$months = 0;
$d1->add(new \DateInterval('P1M'));
while ($d1 <= $d2){
$months ++;
$d1->add(new \DateInterval('P1M'));
}
print_r($months);
Using DateTime, this will give you a more accurate solution for any amount of months:
$d1 = new DateTime("2011-05-14");
$d2 = new DateTime();
$d3 = $d1->diff($d2);
$d4 = ($d3->y*12)+$d3->m;
echo $d4;
You would still need to handle the leftover days $d3->d if your real world problem is not as simple and cut and dry as the original question where both dates are on the first of the month.
This is a simple method I wrote in my class to count the number of months involved into two given dates :
public function nb_mois($date1, $date2)
{
$begin = new DateTime( $date1 );
$end = new DateTime( $date2 );
$end = $end->modify( '+1 month' );
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($begin, $interval, $end);
$counter = 0;
foreach($period as $dt) {
$counter++;
}
return $counter;
}
In case the dates are part of a resultset from a mySQL query, it is much easier to use the TIMESTAMPDIFF function for your date calculations and you can specify return units eg. Select TIMESTAMPDIFF(MONTH, start_date, end_date)months_diff from table_name
strtotime is not very precise, it makes an approximate count, it does not take into account the actual days of the month.
it's better to bring the dates to a day that is always present in every month.
$date1 = "2009-09-01";
$date2 = "2010-05-01";
$d1 = mktime(0, 0, 1, date('m', strtotime($date1)), 1, date('Y', strtotime($date1)));
$d2 = mktime(0, 0, 1, date('m', strtotime($date2)), 1, date('Y', strtotime($date2)));
$total_month = 0;
while (($d1 = strtotime("+1 MONTH", $d1)) <= $d2) {
$total_month++;
}
echo $total_month;
I have used this and works in all conditions
$fiscal_year = mysql_fetch_row(mysql_query("SELECT begin,end,closed FROM fiscal_year WHERE id = '2'"));
$date1 = $fiscal_year['begin'];
$date2 = $fiscal_year['end'];
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$te=date('m',$ts2-$ts1);
echo $te;