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

后端 未结 13 551
我寻月下人不归
我寻月下人不归 2021-02-01 15:07

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:



        
13条回答
  •  隐瞒了意图╮
    2021-02-01 15:16

    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
    

提交回复
热议问题