Getting first day of a given month in PHP? [duplicate] - php

This question already has answers here:
Get which day of the week the month starts on for given input
(2 answers)
Closed 8 years ago.
I've been trying to get the code below to work, and while it worked with June it is not working with July.
The below results in a value of 3 for $first_day_of_month when it should be 2 for Tuesday.
$date = strtotime('20140702'); // July 02, 2014
$month = date('m',$date);
$year = date('Y',$date);
$days_in_month = date('t',$date);
$first_day_of_month = date('w', strtotime($year . $month . 01)); // sunday = 0, saturday = 6

The strtotime function supports relative time formats. You can just do this instead:
$date = strtotime('20140702');
$first_date = strtotime('first day of this month', $date);
$first_day_of_month = date('w', $first_date);
The second parameter to strtotime provides the time that the relative format will be relative to. You can use this to easily calculate dates relative to a particular point, as shown above.

You would have to cast 01 to a string or else php will compute the time for 2014071 rather 20140701
strtotime($year . $month . '01')

You should look at mktime().
In your case your best approach would be:
$date = strtotime('20140702'); // July 02, 2014
$month = date('m',$date);
$year = date('Y',$date);
$days_in_month = date('t',$date);
$first_day_of_month = date('w', mktime(0,0,0,$month,1,$year)); // sunday = 0, saturday = 6
As a bonus you can also get the last day of the month
$last_date_of_month = mktime(0,0,0,$month+1,0,$year);

Related

PHP strtotime returns incorrect month [duplicate]

Current Date is 29th March 2017
When I subtract 2 months using PHP and I get January
$prevmonth = date('M', strtotime('-2 months'));
echo $prevmonth;
But when I subtract 1 month it gives March
$prevmonth = date('M', strtotime('-1 months'));
echo $prevmonth;
strtotime() uses 30 day months and there are only 28 in days in February (this year) so will not yield a valid date in February. You could use the current day d or j and subtract that which will always put you in the previous month (-29 days):
$prevmonth = date('M', strtotime('-' . date('d') . ' days'));
This will get December from January as well.
As covered in the comments, there's no 29th Feb.
29th Feb becomes 1st March.
You may be better to get the current month number, -1 from it, and then get the textual representation.
$prevMonth = date('n') - 1;
$prevMonthText = date('M', mktime(0, 0, 0, $prevMonth, 10));
Or, you could use DateTime if your PHP version allows (it should).
$prevMonth = date('n') - 1;
$dateObj = DateTime::createFromFormat('!m', $prevMonth);
$monthName = $dateObj->format('M'); // March
The only issue with this, that you might have spotted, is January will never return December. A quick ternary statement will catch that.
$prevMonth = ((date('n') - 1) < 1) ? 12 : date('n') - 1;

Get the last day of the current year as date

How can I get the last day (Dec 31) of the current year as a date using PHP?
I tried the following but this doesn't work:
$year = date('Y');
$yearEnd = strtotime($year . '-12-31');
What I need is a date that looks like 2014-12-31 for the current year.
PHP strtotime() uses the current date/time as a basis (so it will use this current year), and you need date() to format:
$yearEnd = date('Y-m-d', strtotime('Dec 31'));
//or
$yearEnd = date('Y-m-d', strtotime('12/31'));
You can just concatenate actual year with required date
$year = date('Y') . '-12-31';
echo $year;
//output 2014-12-31
DateTime is perfectly capable of doing this:
$endOfYear = new \DateTime('last day of December this year');
You can even combine it with more modifiers to get the end of next year:
$endOfNextYear = new \DateTime('last day of December this year +1 years');
Another way to do this is use the Relative Formats of strtotime()
$yearEnd = date('Y-m-d', strtotime('last day of december this year'));
// or
$yearEnd = date('Y-m-d', strtotime('last day of december'));

How to get previous year's date relative to week of year

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 to add 1 month on a date without skipping i.e. february [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP DateTime::modify adding and subtracting months
I have a starting date (i.e. 2011-01-30) and want to add 1 month.
The problem is in defining what a month is. So if I use the following code:
$d1 = DateTime::createFromFormat('Y-m-d H:i:s', '2011-01-30 15:57:57');
$d1->add(new DateInterval('P1M'));
echo $d1->format('Y-m-d H:i:s');
I get the following result: 2011-03-02 15:57:57
The problem is, that I need it to use the following rules:
If I add 1 month it will just add 1 on the month part and leave the day part
(2011-01-15 will become 2011-02-15)
If the day is not existing in the month we will end, we take the last existing day of it
(2011-01-30 will become 2011-02-28)
Is there a common function in php that can do this or do I have to code it by myself?
Maybe I'm just missing a parameter or something!?
It seems that there is no ready function for it, so I wrote it by myself.
This should solve my problem. Thanks anyway for your answers and comments.
If you will find some errors, please provide in the comments.
This function calculates the month and the year I will end in after adding some month. Then it checks if the date is right. If not, we have the case that the day is not in the target month, so we take the last day in the month instead.
Tested with PHP 5.3.10.
<?php
$monthToAdd = 1;
$d1 = DateTime::createFromFormat('Y-m-d H:i:s', '2011-01-30 15:57:57');
$year = $d1->format('Y');
$month = $d1->format('n');
$day = $d1->format('d');
$year += floor($monthToAdd/12);
$monthToAdd = $monthToAdd%12;
$month += $monthToAdd;
if($month > 12) {
$year ++;
$month = $month % 12;
if($month === 0)
$month = 12;
}
if(!checkdate($month, $day, $year)) {
$d2 = DateTime::createFromFormat('Y-n-j', $year.'-'.$month.'-1');
$d2->modify('last day of');
}else {
$d2 = DateTime::createFromFormat('Y-n-d', $year.'-'.$month.'-'.$day);
}
$d2->setTime($d1->format('H'), $d1->format('i'), $d1->format('s'));
echo $d2->format('Y-m-d H:i:s');
You have several alternatives besides DateInterval.
Here are examples that use strtotime():
http://www.brightcherry.co.uk/scribbles/php-adding-and-subtracting-dates/
// Subtracting days from a date
$date = "1998-08-14";
$newdate = strtotime ( '-3 day' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
echo $newdate;
...
// Subtracting months from a date
$date = "1998-08-14";
$newdate = strtotime ( '-3 month' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
echo $newdate;
Here's are some links for DateInterval:
http://php.net/manual/en/dateinterval.construct.php
What can go wrong when adding months with a DateInterval and DateTime::add?
Q: Exactly how do you define a "month"?
Def#1): a "month" is a "month" - regardless of #/days
Def#2): a "month" is 30 days (for example)
Def#3): a "month" is the #/days between the 1st Monday of
subsequent months
etc. etc
Q: What exactly is your "definition"?
OK - as far as I can tell, you still haven't clearly defined what you mean by "month".
But here's one more function that might help:
http://php.net/manual/en/function.getdate.php
/* Function to find the first and last day of the month from the given date.
*
* Author Binu v Pillai binupillai2003#yahoo.com
* #Param String yyyy-mm-dd
*
*/
function findFirstAndLastDay($anyDate)
{
//$anyDate = '2009-08-25'; // date format should be yyyy-mm-dd
list($yr,$mn,$dt) = split('-',$anyDate); // separate year, month and date
$timeStamp = mktime(0,0,0,$mn,1,$yr); //Create time stamp of the first day from the give date.
$firstDay = date('D',$timeStamp); //get first day of the given month
list($y,$m,$t) = split('-',date('Y-m-t',$timeStamp)); //Find the last date of the month and separating it
$lastDayTimeStamp = mktime(0,0,0,$m,$t,$y);//create time stamp of the last date of the give month
$lastDay = date('D',$lastDayTimeStamp);// Find last day of the month
$arrDay = array("$firstDay","$lastDay"); // return the result in an array format.
return $arrDay;
}

How to find first day of the next month and remaining days till this date with 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).

Categories