Use Date Functions in PHP

Helper functions and code to calculate Date/Time calculations in PHP:

Adding months to a Date:

function addMonths($date_str, $months)
{
  $date = new DateTime($date_str);
  $start_day = $date->format('j');

  $date->modify("+{$months} month");
  $end_day = $date->format('j');

  if ($start_day != $end_day)
  $date->modify('last day of last month');

  return $date->format('m/d/Y');
}

Calculating End of Month:

$date = new DateTime('04/23/2012');
$endMonth = $date->format('m/t/Y');

Calculating 1st of Month:

$date = new DateTime('04/23/2012');
$firstMonth = $date->format('m/01/Y');

Using simple english to get it right (recommended way). This does not have any issues calculating next month when current month has 31 days. Usually – +1 Month will add as many days as in current month. So if current month is May (31 days) – adding a month will lead to 31-June which is invalid, so the system will jump to 31-July. Therefore – simple english is much preferrred:

$date = "5/31/2013";
$firstMonth = date('Y-m-01',strtotime($date ."first day of next month")); //"last day of this month" for last day of month

Try this if the above doesn’t work:

$timestamp = strtotime('6/29/2017 9:54:29 AM');
$firstMonth = date('m/d/Y', strtotime("first day of this month", $timestamp));

Get 1 year from given date:

$date = "5/31/2013";
echo "This Year: $date \n";
$nextYear = date('m/d/Y',strtotime($date ."next year"));
echo "Next Year: $nextYear \n";

Useful links :
http://php.net/manual/en/datetime.formats.relative.php
http://stackoverflow.com/questions/1211824/php-strtotime-1month-2month

Advertisements
Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s