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
I have the year, month, week of the month and day of the week. I want to get a date.
For example:
$year = 2019;
$month = 8;
$week = 2; // second week of the month
$day = 2; // tuesday
$date = getDate($year, $month, $week, $day); // $date = '06/08/2019'
You can try to use PHP Relative Formats.
Something like this
$date = new DateTime('first day of August 2019');
$date->modify('tuesday next week');
echo $date->format('Y-m-d');
It needs a little bit of conversion from numbers to strings but it's useful when you need to handle relative dates.
How can I calculate the day of month in PHP with giving month, year, day of week and number of week.
Like, if I have September 2013 and day of week is Friday and number of week is 2, I should get 6. (9/6/2013 is Friday on the 2nd week.)
One way to achieve this is using relative formats for strtotime().
Unfortunately, it's not as straightforward as:
strtotime('Friday of second week of September 2013');
In order for the weeks to work as you mentioned, you need to call strtotime() again with a relative timestamp.
$first_of_month_timestamp = strtotime('first day of September 2013');
$second_week_friday = strtotime('+1 week, Friday', $first_of_month_timestamp);
echo date('Y-m-d', $second_week_friday); // 2013-09-13
Note: Since the first day of the month starts on week one, I've decremented the week accordingly.
I was going to suggest to just use strtotime() in this fashion:
$ts = strtotime('2nd friday of september 2013');
echo date('Y-m-d', $ts), PHP_EOL;
// outputs: 2013-09-13
It seems that this is not how you want the calendar to behave? But it is following a (proper) standard :)
This way its a little longer and obvious but it works.
/* INPUT */
$month = "September";
$year = "2013";
$dayWeek= "Friday";
$week = 2;
$start = strtotime("{$year}/{$month}/1"); //get first day of that month
$result = false;
while(true) { //loop all days of month to find expected day
if(date("w", $start) == $week && date("l", $start) == $dayWeek) {
$result = date("d", $start);
break;
}
$start += 60 * 60 * 24;
}
var_dump($result); // string(2) "06"
How can I get the same day of the same ISO-8601 week number but in the previous year using php?
I am familiar with extracting this soft of information from a time stamp. Is there a built-in way for me to go from day of week, week of year and year to time stamp?
You can use the combination of both date and strtotime like so:
// get the timestamp
$ts = strtotime('today');
// get year, week number and day of week
list($year, $week, $dow) = explode('-', date('Y-W-N', $ts));
// use the "YYYY-WXX-ZZ" format
$format = ($year - 1) . "-W$week-$dow";
echo date('Y-m-d', strtotime($format)), PHP_EOL;
You can do this with strtotime:
$now = time(); // Mon, 12 Nov 2012
$targetYear = date('Y', $now) - 1; // 2011
$targetWeek = date('\\WW-N', $now); // W46-1
$lastYear = strtotime($targetYear . $targetWeek); // Mon, 14 Nov 2011
Try this one:
$date = "2012-11-13";
echo getLastYearWeek($date);
function getLastYearWeek($date)
{
$last_year = date("Y-m-d W N", strtotime("-52 Weeks ".$date));
return $last_year;
}
Or just,
$last_year = date("Y-m-d W N", strtotime("-52 Weeks ".$date));
Use this for reference.
I think you are looking for mktime. have a look here http://php.net/manual/en/function.mktime.php
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).