I'm trying make a function to return the exact date of previous months.
That is a example of my code:
// Dates in TimeStamp
$ts_now = strtotime('now');
$ts_month1 = strtotime("-1 month", $ts_now);
$ts_month2 = strtotime("-2 month", $ts_now);
$ts_month3 = strtotime("-3 month", $ts_now);
// Dates Formated
$date_now = date('Y-m-d', $ts_now);
$date_month1 = date('Y-m-d', $ts_month1);
$date_month2 = date('Y-m-d', $ts_month2);
$date_month3 = date('Y-m-d', $ts_month3);
//Output
echo $date_now; //2020-04-30
echo $date_month1; //2020-03-30
echo $date_month2; //2020-03-01
echo $date_month3; //2020-01-30
The problem is in $date_month2 that represents February, the output is 2020-03-01 instead 2020-02-29 and I suppose that problem will happen in months who have 30 days when present date have 31 days.
What is the best way to resolve that?
As you can see working with the end of the month can be problematic because of how PHP works with dates. Your best bet is to go back to the beginning of the month, do your date math (i.e. go backwards in time), and then go to the date you want. That way you can check to see if the current day is greater than the number of days in month. If so, use the last day of the month instead.
function getMonthsAgo(int $n): string {
$date = new DateTime();
$day = $date->format('j');
$date->modify('first day of this month')->modify('-' . $n . ' months');
if ($day > $date->format('t')) {
$day = $date->format('t');
}
$date->setDate($date->format('Y'), $date->format('m'), $day);
return $date->format('Y-m-d');
}
// Dates Formated
$date_now = date('Y-m-d');
$date_month1 = getMonthsAgo(1);
$date_month2 = getMonthsAgo(2);
$date_month3 = getMonthsAgo(3);
//Output
echo $date_now;
echo $date_month1;
echo $date_month2;
echo $date_month3;
Output:
2020-04-30
2020-03-30
2020-02-29
2020-01-30
This question already has answers here:
Add X Days To Date, Excluding Weekends
(5 answers)
Closed 3 years ago.
I want to find an end date of my first date.
For example my first date is
2020-01-01 04:20:18
And I want to get 20 days after this first date but only the weekdays (exclude the saturday and sunday)
I created this
$expirationDate = date_format(date_add(date_create(date("Y-m-d H:i:s",strtotime($_POST['created_at']))),date_interval_create_from_date_string("20 day")),'Y-m-d H:i:s');
The result I got is
2020-01-21 04:20:18
The end date result should be
2020-01-28 04:20:18
Because date 4,5,11,12,18,19,25,26 is saturday and sunday.
Anyone can help me?
You can use a loop and check which day of the week it is to achieve this. I've left your original $expirationDate calculation in to show the difference in the output:
$dt = date("Y-m-d H:i:s", strtotime('2020-01-01 04:20:18'));
$expirationDate = date_format(date_add(date_create($dt),date_interval_create_from_date_string("20 day")),'Y-m-d H:i:s');
// Add 20 days
for ($i = 0; $i < 20; $i++) {
$dt = date("Y-m-d H:i:s", strtotime("+1 day", strtotime($dt)));
// Is it a Sunday or Saturday?
$day = date('w', strtotime($dt));
if ($day == 0 || $day == 6)
// Deduct one from loop counter
$i--;
}
// Output
echo $dt;
echo $expirationDate;
Output:
$dt = 2020-01-29 04:20:18 (correct)
$expirationDate = 2020-01-21 04:20:18 (incorrect)
How does it work?
It's quite straight-forward:
Store the start date in $dt
Loop from 0 to 19 (for 20 days)
Add one day to $dt
If the day is a Sunday (0) or a Saturday (6), subtract 1 from the loop counter ($i)
An Alternative Solution
As an alternative, this may be greatly simplified by simply adding four weeks to the start time:
$dt = date("Y-m-d H:i:s", strtotime('2020-01-01 04:20:18'));
$dt = date("Y-m-d H:i:s", strtotime("+4 week", strtotime($dt)));
echo $dt;
However, this could only work if that start date was guaranteed to be a weekday. Otherwise you'd end up with an end date on a weekend.
I want to create dynamic expiry date from the today to next 3 months or 6 months or 9 months or 12 months using PHP
I tried but it's not working
$today_date= strtotime(date("Y-m-d"));
$data['expiry_date'] = strtotime(date("Y-m-d", strtotime($valid_months,date("Y-m-d"))));
display code like this
<?php foreach($mydata as value){
$date_expire=date('d M Y',strtotime($value->expiry_date));
$register_date=date_create(date('d M Y ',$value->created));
$expiry_date=date_create($date_expire);
$diff = date_diff($register_date,$expiry_date);
echo $diff->format('%a Days');
}
I am getting output like this
2348824 Days // count remaining days
You could use the DateTime class and the associated methods available such as add and diff
$interval=new DateInterval('P3M');
$now = new DateTime();
$start=new DateTime();
$end=new DateTime( date( DATE_ATOM, strtotime('+1 year') ) );
$end->add( $interval );
while( $start->add( $interval ) <= $end ){
echo $diff = $start->diff( $now )->format('%a') . '<br>';
}
This will output:
92
182
274
366
As far as i understand from your question,i think you just need this.
echo date('d/m/Y', strtotime('+3 months'));
If it Doesn't help , feel free to comment .
I am coming here with a fairly simple (i think) question today. I would like to figure out the past seven days with php
So: I have todays date in variables (like $day = 2, $month = 5, $year = 2013, all put together 2/5/2013), My question is How would i go about getting the past seven days (in the same format) such as in this case
2/5/2013
1/5/2013
30/4/2013
29/4/2013
28/4/2013
27/4/2013
26/4/2013
I have tried subtracting the days for each variable (like $day6 = $todays_date - 1;) but getting month and year changes from that would be quite difficult i believe.
any answers would be appreciated.
Use DateTime class and its modify method
$date = new DateTime();
$yesterday = $date->modify('-1 day');
You could use mktime, and subtract the number of seconds for each day:
$today = mktime(0,0,0,$month,$day,$year);
for($i=0;$i<=6;$i++){
echo date('j/n/Y',$today-($i*(24*60*60))) . '<br />;
}
Try this:
$day = '02/05/2013';
$dates = array();
for($i = 0; $i < 7; $i++){
$dates[] = date('Y-m-d', strtotime($day . ' -' . $i . 'days'));
}
print_r('<pre>');
print_r($dates);
die();
How can I find first day of the next month and the remaining days till this day from the present day?
Thank you
Create a timestamp for 00:00 on the first day of next month:
$firstDayNextMonth = strtotime('first day of next month');
The number of days til that date is the number of seconds between now and then divided by (24 * 60 * 60).
$daysTilNextMonth = ($firstDayNextMonth - time()) / (24 * 3600);
$firstDayNextMonth = date('Y-m-d', strtotime('first day of next month'));
For getting first day after two months from current
$firstDayAfterTwoMonths = date('Y-m-d', strtotime('first day of +2 month'));
You can use DateTime object like this to find out the first day of next month like this:
$date = new DateTime('first day of next month');
You can do this to know how many days left from now to the first day of next month:
$date = new DateTime('now');
$nowTimestamp = $date->getTimestamp();
$date->modify('first day of next month');
$firstDayOfNextMonthTimestamp = $date->getTimestamp();
echo ($firstDayOfNextMonthTimestamp - $nowTimestamp) / 86400;
The easiest and quickest way is to use strtotime() which recognizes 'first day next month';
$firstDayNextMonth = date('Y-m-d', strtotime('first day next month'));
Since I googled this and came to this answer, I figured I'd include a more modern answer that works for PHP 5.3.0+.
//Your starting date as DateTime
$currentDate = new DateTime(date('Y-m-d'));
//Add 1 month
$currentDate->add(new DateInterval('P1M'));
//Get the first day of the next month as string
$firstDayOfNextMonth = $currentDate->format('Y-m-1');
You can get the first of the next month with this:
$now = getdate();
$nextmonth = ($now['mon'] + 1) % 13 + 1;
$year = $now['year'];
if($nextmonth == 1)
$year++;
$thefirst = gmmktime(0, 0, 0, $nextmonth, $year);
With this example, $thefirst will be the UNIX timestamp for the first of the next month. Use date to format it to your liking.
This will give you the remaining days in the month:
$now = getdate();
$months = array(
31,
28 + ($now['year'] % 4 == 0 ? 1 : 0), // Support for leap years!
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
);
$days = $months[$now['mon'] - 1];
$daysleft = $days - $now['mday'];
The number of days left will be stored in $daysleft.
Hope this helps!
$firstDayNextMonth = date('Y-m-d', mktime(0, 0, 0, date('m')+1, 1, date('Y')));
As another poster has mentioned the DateInterval object does not give accurate results for the next month when you use dates such as 1/31/2016 or 8/31/2016 as it skips the next month. My solution was to still use the DateInterval object but reformat your current date to be the first day of the current month prior to utilizing the DateInterval.
$currentDate = '8/31/2016';
$date = new DateTime(date("n", strtotime($currentDate))."/1/".date("Y", strtotime($currentDate)));
//add 1 month
$date->add(new DateInterval('P1M'));
$currentDate=$date->format('m/1/Y');
echo($currentDate);
easiest way to get the last day of the month
date('Y-m-d', mktime(0, 0, 0, date('m')+1, 1, date('Y')));
I took mattbasta's approach because it's able to get the 'first day of next month' with a given date, but there is a tiny problem in calculating the $nextmonth. The fix is as below:
$now = getdate();
$nextmonth = ($now['mon'] + 1) % 13 + 1;
$year = $now['year'];
if($nextmonth == 1)
$year++;
else
$nextmonth--;
$thefirst = gmmktime(0, 0, 0, $nextmonth, $year);
I initially thought about using a DateInterval object (as discussed above in another answer) but it is not reliable. For example, if the current DateTime is 31 January and then we add on a month (to get the next month) then it will skip February completely!
Here is my solution:
function start_of_next_month(DateTime $datetime)
{
$year = (int) $datetime->format('Y');
$month = (int) $datetime->format('n');
$month += 1;
if ($month === 13)
{
$month = 1;
$year += 1;
}
return new DateTime($year . '-' . $month . '-01');
}
Even easier way to get first and last day of next month
$first = strttotime("first day of next month");
$last = strttotime("last day of next month");
You could do something like this. To have this functionality, you need to make use of a php library available in https://packagist.org/packages/ishworkh/navigable-date.
With that is really easy to do what you're asking for here.
For e.g:
$format = 'Y-m-d H:i:s';
$Date = \NavigableDate\NavigableDateFacade::create('2017-02-24');
var_dump($Date->format($format));
$resetTime = true;
$resetDays = true;
$NextMonth = $Date->nextMonth($resetTime, $resetDays);
var_dump($NextMonth->format($format));
$DayUntilFirstOfNextMonth = $NextMonth->getDifference($Date);
var_dump('Days left:' . $DayUntilFirstOfNextMonth->format('%d'));
gives you ouput:
string(19) "2017-02-24 00:00:00"
string(19) "2017-03-01 00:00:00"
string(11) "Days left:5"
Note: Additionally this library let you navigate through dates by day(s), week(s), year(s) forward or backward. For more information look into its README.
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
To get the first day of next month a clean solution:
<?php
$date = new DateTimeInmutable('now');
$date->modify('first day of next month');//here the magic occurs
echo $date->format('Y-m-d') . '\n';
Since you just want to calculate it I suggest using DateTimeInmutable class.
using the class DateTime and $date->modify('first day of next month'); will modify your original date value.
$month = date('m')+1;
if ($month<10) {
$month = '0'.$month;
}
echo date('Y-').$month.'-01';
Simplest way to achieve this. You can echo or store into variable.
I came up with this for my needs:
if(date('m') == 12) { $next_month = 1; } else { $next_month = date('m')+1; }
if($next_month == 1) { $year_start = date('Y')+1; } else { $year_start = date('Y'); }
$date_start_of_next_month = $year_start . '-' . $next_month . '-01 00:00:00';
if($next_month == 12) { $month_after = 1; } else { $month_after = $next_month+1; }
if($month_after == 1) { $year_end = date('Y')+1; } else { $year_end = date('Y'); }
$date_start_of_month_after_next = $year_end . '-' . $month_after . '-01 00:00:00';
Please note that instead of getting $date_end_of_next_month I chose to go with a $date_start_of_month_after_next date, it avoids the hassles with leap years and months containing different number of days.
You can simply use the >= comparaision sign for $date_start_of_next_month and the < one for $date_start_of_month_after_next.
If you prefer a timestamp format for the date, from there you will want to apply the strtotime() native function of PHP on these two variables.
You can use the php date method to find the current month and date, and then you would need to have a short list to find how many days in that month and subtract (leap year would require extra work).