[php] How do I get next month date from today's date and insert it in my database?

I have two columns in my db: start_date and end_date, which are both DATE types. My code is updating the dates as follows:

$today_date = date("Y-m-d");
$end_date = date("Y-m-d"); // date +1 month ??

$sql1 = "UPDATE `users` SET `start_date` = '".$today_date."', `end_date` = '".$end_date."'  WHERE `users`.`id` ='".$id."' LIMIT 1 ;";

What is the best way to make $end_date equal to $start_date + one month? For example, 2000-10-01 would become 2000-11-01.

This question is related to php mysql date

The answer is


You can use strtotime() as in Gazler's example, which is great for this case.

If you need more complicated control use mktime().

$end_date = mktime(date("H"), date("i"), date("s"), date("n") + 1, date("j"), date("Y"));

The accepted answer works only if you want exactly 31 days later. That means if you are using the date "2013-05-31" that you expect to not be in June which is not what I wanted.

If you want to have the next month, I suggest you to use the current year and month but keep using the 1st.

$date = date("Y-m-01");
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;

This way, you will be able to get the month and year of the next month without having a month skipped.


This function returns any correct number of months positively or negatively. Found in the comment section here:

function addMonthsToTime($numMonths = 1, $timeStamp = null){
    $timeStamp === null and $timeStamp = time();//Default to the present
    $newMonthNumDays =  date('d',strtotime('last day of '.$numMonths.' months', $timeStamp));//Number of days in the new month
    $currentDayOfMonth = date('d',$timeStamp);

    if($currentDayOfMonth > $newMonthNumDays){
      $newTimeStamp = strtotime('-'.($currentDayOfMonth - $newMonthNumDays).' days '.$numMonths.' months', $timeStamp);
    } else {
    $newTimeStamp = strtotime($numMonths.' months', $timeStamp);
    }

    return $newTimeStamp;
}

Be careful, because sometimes strtotime("+1 months") can skip month numbers.

Example:

$today = date("Y-m-d"); // 2012-01-30
$next_month = date("Y-m-d", strtotime("$today +1 month"));

If today is January, next month should be February which has 28 or 29 days, but PHP will return March as next month, not February.


date("Y-m-d",strtotime("last day of +1 month",strtotime($anydate)))

one way of doing this is- first getting last date of current month and then adding 1 day to it, to get next month's first date. This will prevent us from unintentional skipping of months which occurs while using '+1 month'.

$today_date = date("Y-m-d"); 
$last_date_of_month=date('Y-m-t',strtotime($today_date);//get last date of current month
$last_day_of_month_proper =strtotime($last_day_of_month);
$new_date=date('Y-m-d', strtotime('+1 day',$last_day_of_month_proper)); 
echo $new_date;

Adding my solution here, as this is the thread that comes in google search. This is to get the next date of month, fixing any skips, keeping the next date within next month.

PHP adds current months total number of days to current date, if you do +1 month for example.

So applying +1 month to 30-01-2016 will return 02-03-2016. (Adding 31 days)

For my case, I needed to get 28-02-2016, so as to keep it within next month. In such cases you can use the solution below.

This code will identify if the given date's day is greater than next month's total days. If so It will subtract the days smartly and return the date within the month range.

Do note the return value is in timestamp format.

function getExactDateAfterMonths($timestamp, $months){
    $day_current_date            = date('d', $timestamp);
    $first_date_of_current_month = date('01-m-Y', $timestamp);
    // 't' gives last day of month, which is equal to no of days
    $days_in_next_month          = date('t',  strtotime("+".$months." months", strtotime($first_date_of_current_month)));

    $days_to_substract = 0;
    if($day_current_date > $days_in_next_month)
         $days_to_substract = $day_current_date - $days_in_next_month;

    $php_date_after_months   = strtotime("+".$months." months", $timestamp);
    $exact_date_after_months = strtotime("-".$days_to_substract." days", $php_date_after_months);

    return $exact_date_after_months;
}

getExactDateAfterMonths(strtotime('30-01-2016'), 1);
// $php_date_after_months   => 02-03-2016
// $exact_date_after_months => 28-02-2016

I think this is similar to kouton's answer, but this one just takes in a timeStamp and returns a timestamp SOMEWHERE in the next month. You could use date("m", $nextMonthDateN) from there.

function nextMonthTimeStamp($curDateN){ 
   $nextMonthDateN = $curDateN;
   while( date("m", $nextMonthDateN) == date("m", $curDateN) ){
      $nextMonthDateN += 60*60*24*27;
   }
   return $nextMonthDateN; //or return date("m", $nextMonthDateN);
}

01-Feb-2014

$date = mktime( 0, 0, 0, 2, 1, 2014 );

echo strftime( '%d %B %Y', strtotime( '+1 month', $date ) );

You do not actually need PHP functions to achieve this. You can already do simple date manipulations directly in SQL, for example:

$sql1 = "
    UPDATE `users` SET 
    `start_date` = CURDATE(), 
    `end_date` = DATE_ADD(CURDATE(), INTERVAL 1 MONTH)  
    WHERE `users`.`id` = '" . $id . "';
";

Refer to http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_addtime


I know - sort of late. But I was working at the same problem. If a client buys a month of service, he/she expects to end it a month later. Here's how I solved it:

    $now = time(); 
    $day = date('j',$now);
    $year = date('o',$now);
    $month = date('n',$now);
    $hour = date('G');
    $minute = date('i');
    $month += $count;
    if ($month > 12)        {
            $month -= 12;
            $year++; 
            }
    $work = strtotime($year . "-" . $month . "-01");
    $avail = date('t',$work);
    if ($day > $avail)
            $day = $avail;
    $stamp = strtotime($year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute);

This will calculate the exact day n*count months from now (where count <= 12). If the service started March 31, 2019 and runs for 11 months, it will end on Feb 29, 2020. If it runs for just one month, the end date is Apr 30, 2019.


$nextm = date('m', strtotime('+1 month', strtotime(date('Y-m-01'))));


If you want a specific date in next month, you can do this:

// Calculate the timestamp
$expire = strtotime('first day of +1 month');

// Format the timestamp as a string
echo date('m/d/Y', $expire);

Note that this actually works more reliably where +1 month can be confusing. For example...

Current Day   | first day of +1 month     | +1 month
---------------------------------------------------------------------------
2015-01-01    | 2015-02-01                | 2015-02-01
2015-01-30    | 2015-02-01                | 2015-03-02  (skips Feb)
2015-01-31    | 2015-02-01                | 2015-03-03  (skips Feb)
2015-03-31    | 2015-04-01                | 2015-05-01  (skips April)
2015-12-31    | 2016-01-01                | 2016-01-31

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?