Related
Ok so I want to get the Monday of week 16 in 2010 (more precisely to week $week of year $year). here is what I have in my test.php file
$week = 16;
$year = 2010;
$dateString = $dateString = 'Start of week ' . $week . ' in ' . $year;
$date = strtotime( $dateString );
echo $date;
The value returned is false. I have also tried using Monday of week... but this also gave a false result.
any idea how to get a date given a week number and the year?
thanks
I'd recommend using the builtin \DateTime class.
Inspired by the answer here I tested the following code:
<?php
function getStartDate($week, $year) {
$dto = new DateTime();
$dto->setISODate($year, $week);
return $dto->format('Y-m-d');
}
$week = 16;
$year = 2010;
var_dump(getStartDate($week, $year));
This returned the following:
/some/fancy/path/test.php:12:string '2010-04-19' (length=10)
Monday is the first day of the week. Make use of setISODate()
<?php
$gendate = new DateTime();
$gendate->setISODate(2022,2,1); //year , week num , day
echo $gendate->format('d-m-Y'); //"prints" 10-01-2022
What I Require
I have a certain list of datetimes. I want to get the first monday of each datetimes.
eg: Suppose the given datetimes are
2013-07-05 2013-08-05, 2013-09-13 etc.
I want to get the first monday of all these datetimes such that the output results in
2013-07-01, 2013-08-05, 2013-09-02 respectively
I am actually stuck with this using stftime.
strftime("%d/%m/%Y", strtotime("first Monday of July 2012"));
Using php Datetime class:
$Dates = array('2013-07-02', '2013-08-05', '2013-09-13');
foreach ($Dates as $Date)
{
$test = new DateTime($Date);
echo $test->modify('first monday')->format('Y-m-d');
}
<?php
function find_the_first_monday($date)
{
$time = strtotime($date);
$year = date('Y', $time);
$month = date('m', $time);
for($day = 1; $day <= 31; $day++)
{
$time = mktime(0, 0, 0, $month, $day, $year);
if (date('N', $time) == 1)
{
return date('Y-m-d', $time);
}
}
}
echo find_the_first_monday('2013-07-05'), "\n";
echo find_the_first_monday('2013-08-05'), "\n";
echo find_the_first_monday('2013-09-13'), "\n";
// output:
// 2013-07-01
// 2013-08-05
// 2013-09-02
the first monday would be within the first 7 days of a month,
DAYOFWEEK(date) returns 1=sunday, 2=monday, and so on
also see the hack#23
http://oreilly.com/catalog/sqlhks/chapter/ch04.pdf
I know this is an old question and my answer is not 100% solution for this question, but this might be usefull for someone, this will give "first Saturday of the given year/month":
date("Y-m-d", strtotime("First Saturday of 2021-08")); // gives: 2021-08-07
You can manipulate this in many ways.
obviously you can put "Second Saturday of year-month" and it will find that as well.
Works with PHP 5.3.0 and above (tested at https://sandbox.onlinephpfunctions.com/).
You could loop through the array of dates and then break out of the loop and return the $Date when you first encounter Monday
PHPFIDDLE
$Dates = array('2013-07-02', '2013-08-05', '2013-09-13');
foreach ($Dates as $Date)
{
$weekday = date('l', strtotime($Date));
if($weekday == 'Monday') {
echo "First Monday in list is - " . $Date;
break;
}
}
Output
First Monday in list is - 2013-08-05
I've looked at at least 2 dozen topics about this and haven't really found a good answer yet, so I come to you to ask once again for answers regarding the dreaded topic of Repeating Events.
I've got Daily, Weekly, Monthly, and Yearly repeats working out fine for now (I still need to revamp the system with Exception events and whatnot, but it works for the time being). But, we want to be able to add the ability to repeat events on the (1st,2nd,3rd,4th,5th) [Sun|Mon|Tue|Wed|Thu|Fri|Sat] of every month, every other month, and every three months.
Now, if I can just understand the logic for the every month, I can figure out the every other month and the every three months.
Here's a bit of what I have so far (note: I'm not saying I have the best way of doing it or anything, but the system is one we update very slowly over time when we aren't busy with other projects, so I make the code more efficient as I have the time).
First I get the starting and ending dates formatted for date calculations:
$ending = $_POST['end_month'] . "/" . $_POST['end_day'] . "/" . substr($_POST['end_year'], 2, 2);
$starting = $_POST['month'] . "/" . $_POST['day'] . "/" . substr($_POST['year'], 2, 2);
Then I get the difference between those two to know how many times to repeat using a function I'm fairly certain I found on here some time ago and dividing that amount by 28 days to get just about how many TIMES it needs to repeat so that there is one a month:
$repeat_number = date_diff($starting, $ending) / 28;
//find the difference in DAYS between the two dates
function date_diff($old_date, $new_date) {
$offset = strtotime($new_date) - strtotime($old_date);
return $offset/60/60/24;
}
Then I add the (1st,2nd,etc...) part to the [Sun|Mon|etc...] part to figure out what they are looking for giving me somehthing like 'first Sunday' :
$find = $_POST['custom_number']. ' ' . $_POST['custom_day'];
Then I use a loop that runs the number of times this needs to repeat (the $repeat_number from above):
for($m = 0; $m <= $repeat_number; $m++) {
if($m == 0) {
$month = date('F', substr($starting,0,2));
} else {
$month = date('F', strtotime($month . ' + ' . $m . ' months'));
}
$repeat_date = strtotime($find . ' in ' . $month);
}
Now, I'm aware this code doesn't work, I at one time did have code that turned up the correct month and year for the repeat, but wouldn't necessarily find the first tuesday or whatever it was that was being looked for.
If anyone could point me back in the right direction, it would be most appreciated. I've been lurking in the community for some time now, just started trying to actively participate recently.
Thanks in advance for any input or advice you can provide.
Here's a possible alternative for you. strtotime is powerful, and the syntax includes really useful bits like comprehensive relative time and date wording.
You can use it to generate the first through Nth specific weekdays of a specific month by using the format " of ". Here's an example using date_create to invoke a DateTime object, but regular old strtotime works the same way:
php > $d = date_create('Last Friday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Friday March 25 2011 00:00:00
php > $d = date_create('First Friday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Friday March 04 2011 00:00:00
php > $d = date_create('First Sunday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Sunday March 06 2011 00:00:00
php > $d = date_create('Fourth Sunday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Sunday March 27 2011 00:00:00
php > $d = date_create('Last Sunday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Sunday March 27 2011 00:00:00
It will also overflow the month, if you ask for an invalid one:
php > $d = date_create('Ninth Sunday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Sunday May 01 2011 00:00:00
Note that it only works with the ordinal number wording. You can't pass "1st" or "3rd", unfortunately.
Once you use this to grab the proper Nth weekday, you can then simply add the number of needed weekdays to skip (7 for one week, 14 for two, 21 for three, etc) as required until the designated end date or designated number of weeks has passed. Once again, strtotime to the rescue, using the second argument to chain together relativeness:
php > echo date('l F d Y H:i:s', strtotime('+14 days', strtotime('First Thursday of March 2011')));
Thursday March 17 2011 00:00:00
(My local copy also accepted '+14 days First Thursday of March 2011', but that felt kind of weird.)
I have a more simple method, although it may seem hack-ish.
What we can do is take the start date, and infer it's "n" value from it by taking the ceiling of its day divided by 7.
For example, if your start date is the 18th, we divide by 7 and take the ceiling to infer that it is the 3rd "whatever-day" of the month.
From there we can simply repeatedly add 7 days to this to get a new date, and whenever the new date's ceilinged 7-quotient is 3, we've hit the next "nth whatever-day" of the month.
Some code can be seen below:
$day_nth = ceil(date("j", strtotime($date))/7);
for ($i = 0; $i < $number_of_repeats; $i++) {
while (ceil(date("j", strtotime($date))/7) != $day_nth)
$date = date("Y-m-d", strtotime("+7 days", strtotime($date)));
/* Add your event, or whatever */
/* Now we increment date by 7 days before the loop starts again,
** otherwise the while loop would never execute and we'd just be
** adding to the same date repeatedly. */
$date = date("Y-m-d", strtotime("+7 days", strtotime($date)));
}
What's nice about this method is that we don't even have to concern ourselves with which day of the week we're dealing with. We just infer everything from the start date and away we go.
I make it like that:
//$typeOfDate = 0;
$typeOfDate = 1;
$day = strtotime("2013-02-01");
$to = strtotime(date("Y-m-d", $day) . " +6 month");
if ($typeOfDate == 0) { //use the same day (number) of the month
$dateArray[] = date("Y-m-d", $day);
$event_day_number = date("d", $day);
while ($day <= $to) {
$nextMonth = date("m", get_x_months_to_the_future($day));
$day = strtotime(date("Y-" . $nextMonth . "-d", $day));
$dateArray[] = date("Y-m-d", $day);
}
}
if ($typeOfDate == 0) { //use the same day (like friday) of the month
$dateArray[] = date("Y-m-d", $day);
$monthEvent = date("m", $day);
$day = strtotime(date("Y-m-d", $day) . " +4 weeks");
$newMonthEvent = date("m", $day);
if ($monthEvent == $newMonthEvent) {
$day = strtotime(date("Y-m-d", $day) . " +7 days");
}
while ($day <= $to) {
$dateArray[] = date("Y-m-d", $day);
$monthEvent = date("m", $day);
$day = strtotime(date("Y-m-d", $day) . " +4 weeks");
$newMonthEvent = date("m", $day);
if ($monthEvent == $newMonthEvent) {
$day = strtotime(date("Y-m-d", $day) . " +7 days");
}
}
}
Let's say I have a date in the following format: 2010-12-11 (year-mon-day)
With PHP, I want to increment the date by one month, and I want the year to be automatically incremented, if necessary (i.e. incrementing from December 2012 to January 2013).
Regards.
$time = strtotime("2010.12.11");
$final = date("Y-m-d", strtotime("+1 month", $time));
// Finally you will have the date you're looking for.
I needed similar functionality, except for a monthly cycle (plus months, minus 1 day). After searching S.O. for a while, I was able to craft this plug-n-play solution:
function add_months($months, DateTime $dateObject)
{
$next = new DateTime($dateObject->format('Y-m-d'));
$next->modify('last day of +'.$months.' month');
if($dateObject->format('d') > $next->format('d')) {
return $dateObject->diff($next);
} else {
return new DateInterval('P'.$months.'M');
}
}
function endCycle($d1, $months)
{
$date = new DateTime($d1);
// call second function to add the months
$newDate = $date->add(add_months($months, $date));
// goes back 1 day from date, remove if you want same day of month
$newDate->sub(new DateInterval('P1D'));
//formats final date to Y-m-d form
$dateReturned = $newDate->format('Y-m-d');
return $dateReturned;
}
Example:
$startDate = '2014-06-03'; // select date in Y-m-d format
$nMonths = 1; // choose how many months you want to move ahead
$final = endCycle($startDate, $nMonths); // output: 2014-07-02
Use DateTime::add.
$start = new DateTime("2010-12-11", new DateTimeZone("UTC"));
$month_later = clone $start;
$month_later->add(new DateInterval("P1M"));
I used clone because add modifies the original object, which might not be desired.
strtotime( "+1 month", strtotime( $time ) );
this returns a timestamp that can be used with the date function
You can use DateTime::modify like this :
$date = new DateTime('2010-12-11');
$date->modify('+1 month');
See documentations :
https://php.net/manual/en/datetime.modify.php
https://php.net/manual/en/class.datetime.php
UPDATE january 2021 : correct mistakes raised by comments
This solution has some problems for months with 31 days like May etc.
Exemple : this jumps from 31st May to 1st July which is incorrect.
To correct that, you can create this custom function
function addMonths($date,$months){
$init=clone $date;
$modifier=$months.' months';
$back_modifier =-$months.' months';
$date->modify($modifier);
$back_to_init= clone $date;
$back_to_init->modify($back_modifier);
while($init->format('m')!=$back_to_init->format('m')){
$date->modify('-1 day') ;
$back_to_init= clone $date;
$back_to_init->modify($back_modifier);
}
}
Then you can use it like that :
$date = new DateTime('2010-05-31');
addMonths($date, 1);
print_r($date);
//DateTime Object ( [date] => 2010-06-30 00:00:00.000000 [timezone_type] => 3 [timezone] => Europe/Berlin )
This solution was found in PHP.net posted by jenspj : https://www.php.net/manual/fr/datetime.modify.php#107592
(date('d') > 28) ? date("mdY", strtotime("last day of next month")) : date("mdY", strtotime("+1 month"));
This will compensate for February and the other 31 day months. You could of course do a lot more checking to to get more exact for 'this day next month' relative date formats (which does not work sadly, see below), and you could just as well use DateTime.
Both DateInterval('P1M') and strtotime("+1 month") are essentially blindly adding 31 days regardless of the number of days in the following month.
2010-01-31 => March 3rd
2012-01-31 => March 2nd (leap year)
Please first you set your date format as like 12-12-2012
After use this function it's work properly;
$date = date('d-m-Y',strtotime("12-12-2012 +2 Months");
Here 12-12-2012 is your date and +2 Months is increment of the month;
You also increment of Year, Date
strtotime("12-12-2012 +1 Year");
Ans is 12-12-2013
I use this way:-
$occDate='2014-01-28';
$forOdNextMonth= date('m', strtotime("+1 month", strtotime($occDate)));
//Output:- $forOdNextMonth=02
/*****************more example****************/
$occDate='2014-12-28';
$forOdNextMonth= date('m', strtotime("+1 month", strtotime($occDate)));
//Output:- $forOdNextMonth=01
//***********************wrong way**********************************//
$forOdNextMonth= date('m', strtotime("+1 month", $occDate));
//Output:- $forOdNextMonth=02; //instead of $forOdNextMonth=01;
//******************************************************************//
Just updating the answer with simple method for find the date after no of months. As the best answer marked doesn't give the correct solution.
<?php
$date = date('2020-05-31');
$current = date("m",strtotime($date));
$next = date("m",strtotime($date."+1 month"));
if($current==$next-1){
$needed = date('Y-m-d',strtotime($date." +1 month"));
}else{
$needed = date('Y-m-d', strtotime("last day of next month",strtotime($date)));
}
echo "Date after 1 month from 2020-05-31 would be : $needed";
?>
If you want to get the date of one month from now you can do it like this
echo date('Y-m-d', strtotime('1 month'));
If you want to get the date of two months from now, you can achieve that by doing this
echo date('Y-m-d', strtotime('2 month'));
And so on, that's all.
Thanks Jason, your post was very helpful. I reformatted it and added more comments to help me understand it all. In case that helps anyone, I have posted it here:
function cycle_end_date($cycle_start_date, $months) {
$cycle_start_date_object = new DateTime($cycle_start_date);
//Find the date interval that we will need to add to the start date
$date_interval = find_date_interval($months, $cycle_start_date_object);
//Add this date interval to the current date (the DateTime class handles remaining complexity like year-ends)
$cycle_end_date_object = $cycle_start_date_object->add($date_interval);
//Subtract (sub) 1 day from date
$cycle_end_date_object->sub(new DateInterval('P1D'));
//Format final date to Y-m-d
$cycle_end_date = $cycle_end_date_object->format('Y-m-d');
return $cycle_end_date;
}
//Find the date interval we need to add to start date to get end date
function find_date_interval($n_months, DateTime $cycle_start_date_object) {
//Create new datetime object identical to inputted one
$date_of_last_day_next_month = new DateTime($cycle_start_date_object->format('Y-m-d'));
//And modify it so it is the date of the last day of the next month
$date_of_last_day_next_month->modify('last day of +'.$n_months.' month');
//If the day of inputted date (e.g. 31) is greater than last day of next month (e.g. 28)
if($cycle_start_date_object->format('d') > $date_of_last_day_next_month->format('d')) {
//Return a DateInterval object equal to the number of days difference
return $cycle_start_date_object->diff($date_of_last_day_next_month);
//Otherwise the date is easy and we can just add a month to it
} else {
//Return a DateInterval object equal to a period (P) of 1 month (M)
return new DateInterval('P'.$n_months.'M');
}
}
$cycle_start_date = '2014-01-31'; // select date in Y-m-d format
$n_months = 1; // choose how many months you want to move ahead
$cycle_end_date = cycle_end_date($cycle_start_date, $n_months); // output: 2014-07-02
function dayOfWeek($date){
return DateTime::createFromFormat('Y-m-d', $date)->format('N');
}
Usage examples:
echo dayOfWeek(2016-12-22);
// "4"
echo dayOfWeek(date('Y-m-d'));
// "4"
$date = strtotime("2017-12-11");
$newDate = date("Y-m-d", strtotime("+1 month", $date));
If you want to increment by days you can also do it
$date = strtotime("2017-12-11");
$newDate = date("Y-m-d", strtotime("+5 day", $date));
For anyone looking for an answer to any date format.
echo date_create_from_format('d/m/Y', '15/04/2017')->add(new DateInterval('P1M'))->format('d/m/Y');
Just change the date format.
//ECHO MONTHS BETWEEN TWO TIMESTAMPS
$my_earliest_timestamp = 1532095200;
$my_latest_timestamp = 1554991200;
echo '<pre>';
echo "Earliest timestamp: ". date('c',$my_earliest_timestamp) ."\r\n";
echo "Latest timestamp: " .date('c',$my_latest_timestamp) ."\r\n\r\n";
echo "Month start of earliest timestamp: ". date('c',strtotime('first day of '. date('F Y',$my_earliest_timestamp))) ."\r\n";
echo "Month start of latest timestamp: " .date('c',strtotime('first day of '. date('F Y',$my_latest_timestamp))) ."\r\n\r\n";
echo "Month end of earliest timestamp: ". date('c',strtotime('last day of '. date('F Y',$my_earliest_timestamp)) + 86399) ."\r\n";
echo "Month end of latest timestamp: " .date('c',strtotime('last day of '. date('F Y',$my_latest_timestamp)) + 86399) ."\r\n\r\n";
$sMonth = strtotime('first day of '. date('F Y',$my_earliest_timestamp));
$eMonth = strtotime('last day of '. date('F Y',$my_earliest_timestamp)) + 86399;
$xMonth = strtotime('+1 month', strtotime('first day of '. date('F Y',$my_latest_timestamp)));
while ($eMonth < $xMonth) {
echo "Things from ". date('Y-m-d',$sMonth) ." to ". date('Y-m-d',$eMonth) ."\r\n\r\n";
$sMonth = $eMonth + 1; //add 1 second to bring forward last date into first second of next month.
$eMonth = strtotime('last day of '. date('F Y',$sMonth)) + 86399;
}
I find the mtkime() function works really well for this:
$start_date="2021-10-01";
$start_date_plus_a_month=date("Y-m-d", mktime(0, 0, 0, date("m",strtotime($start_date))+1, date("d",strtotime($start_date)), date("Y",strtotime($start_date))));
result: 2021-11-01
I like to subtract 1 from the 'day' to produce '2021-10-31' which can be useful if you want to display a range across 12 months, e.g. Oct 1, 2021 to Sep 30 2022
$start_date_plus_a_year=date("Y-m-d", mktime(0, 0, 0, date("m",strtotime($start_date))+12, date("d",strtotime($start_date))-1, date("Y",strtotime($start_date))));
result: 2022-09-30
The correct answer to the exact question asked is Giuseppe Canale's answer from earlier. I'm going to answer a slightly more generic question of how to increment the date by an arbitrary number of months, however.
<?php
/**
* Will return a timestamp corresponding to first day of the month that is N months into the future.
* #param int $months_later number of months into the future: 0 for current one
* #param string $today if supplied will be used as the "now" time
* #return int
*/
function rel_month_to_time($months_later, $today=null) {
if ($months_later===0) {
return is_null($today) ? time() : strtotime($today);
}
return strtotime('first day of next month', rel_month_to_time($months_later-1, $today));
}
As is many times the case, you can use recursion for these "human problems" like calendars. The above can be used to return a timestamp corresponding to "next month" -- the way we humans think of it.
<?php echo date('Y-m-d', rel_month_to_time(1, '2023-01-30'));
// 2023-02-01
As pointed by #NetVicious i corrected the code, it should work with all dates, some example:
2013-01-30 will be 2013-02-28
2013-05-15 will be 2013-05-15
2013-05-31 will be 2013-06-30
This code uses the DateTime class to create a new date object, then it adds 1 month to the date using the modify method. Next, it gets the day of the next month using the format method. If the next month's day doesn't match the original day, it modifies the date to the last day of the previous month using the modify method.
$original_date = "2013-01-30";
$original_day = date("d", strtotime($original_date));
$date = new DateTime($original_date);
$date->modify('+1 month');
$next_month_day = $date->format('d');
if ($next_month_day != $original_day) {
$date->modify('last day of previous month');
}
$new_date = $date->format('Y-m-d');
echo $new_date;
All presented solutions are not working properly.
strtotime() and DateTime::add or DateTime::modify give sometime invalid results.
Examples:
- 31.08.2019 + 1 month gives 01.10.2019 instead 30.09.2019
- 29.02.2020 + 1 year gives 01.03.2021 instead 28.02.2021
(tested on PHP 5.5, PHP 7.3)
Below is my function based on idea posted by Angelo that solves the problem:
// $time - unix time or date in any format accepted by strtotime() e.g. 2020-02-29
// $days, $months, $years - values to add
// returns new date in format 2021-02-28
function addTime($time, $days, $months, $years)
{
// Convert unix time to date format
if (is_numeric($time))
$time = date('Y-m-d', $time);
try
{
$date_time = new DateTime($time);
}
catch (Exception $e)
{
echo $e->getMessage();
exit;
}
if ($days)
$date_time->add(new DateInterval('P'.$days.'D'));
// Preserve day number
if ($months or $years)
$old_day = $date_time->format('d');
if ($months)
$date_time->add(new DateInterval('P'.$months.'M'));
if ($years)
$date_time->add(new DateInterval('P'.$years.'Y'));
// Patch for adding months or years
if ($months or $years)
{
$new_day = $date_time->format("d");
// The day is changed - set the last day of the previous month
if ($old_day != $new_day)
$date_time->sub(new DateInterval('P'.$new_day.'D'));
}
// You can chage returned format here
return $date_time->format('Y-m-d');
}
Usage examples:
echo addTime('2020-02-29', 0, 0, 1); // add 1 year (result: 2021-02-28)
echo addTime('2019-08-31', 0, 1, 0); // add 1 month (result: 2019-09-30)
echo addTime('2019-03-15', 12, 2, 1); // add 12 days, 2 months, 1 year (result: 2019-09-30)
put a date in input box then click the button get day from date in jquery
$(document).ready( function() {
$("button").click(function(){
var day = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var a = new Date();
$(".result").text(day[a.getDay()]);
});
});
<?php
$selectdata ="select fromd,tod from register where username='$username'";
$q=mysqli_query($conm,$selectdata);
$row=mysqli_fetch_array($q);
$startdate=$row['fromd'];
$stdate=date('Y', strtotime($startdate));
$endate=$row['tod'];
$enddate=date('Y', strtotime($endate));
$years = range ($stdate,$enddate);
echo '<select name="years" class="form-control">';
echo '<option>SELECT</option>';
foreach($years as $year)
{ echo '<option value="'.$year.'"> '.$year.' </option>'; }
echo '</select>'; ?>
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).